I have to write a method to switch the first and last letter of a string. For example the string "java" would become "aavj".
Here is what I have so far:
import javax.swing.JOptionPane;
public class printTest {
public static void main(String[] args) {
String password;
password = JOptionPane.showInputDialog("Please input your password");
int length = password.length();
String firstChar = password.substring(0, 1);
String lastChar = password.substring(length - 1);
password = lastChar + password + firstChar;
JOptionPane.showMessageDialog(null, password);
}
}
With that code I get the following output "ajavaj" when I input "java", so how can I fix this? I need to switch the first two letters and still have the middle of the string. What should I do?
You need to substring password on this line:
password = lastChar + password.substring(1, length-1) + firstChar;
By doing password = lastChar + password + firstChar;
you are concatenating the original password String with the two other Strings i.e. lastChar
& firstChar
. By doing this you will actually get a new String with lastChar
and firstChar
appended and not swapped.
Also, Strings are immutable and every time you are trying to manipulate it, you are ending up creating a new String. You should use char
array instead to avoid this problem.
Try this piece of code:
import javax.swing.JOptionPane;
public class printTest
{
public static void main(String[] args)
{
/* Capture Password */
String password = JOptionPane.showInputDialog("Please input your password");
char[] pass = password.toCharArray();
/* Swap Logic */
char temp = pass[0];
pass[0] = pass[pass.length - 1];
pass[pass.length - 1] = temp;
/* Show MessageDialog */
JOptionPane.showMessageDialog(null, new String(pass));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With