I am trying to make a user input be inverted to what they put in so for example if they put in helloWorld it would output to HELLOwORLD but for some reason, my code is not working and I don't know how to fix it.
import javax.swing.JOptionPane;
String originalText = JOptionPane.showInputDialog
("Enter a short phrase:"); //to get the userInput text
for(int i=0; i <= originalText.length(); i++)
{
if(originalText.charAt(i).isUpperCase())
{
originalText.charAt(i).toLowerCase();
}
else if(originalText.charAt(i).isLowerCase())
{
originalText.charAt(i).toUpperCase();
}
}
The function toLowerCase()
and toUpperCase()
are methods of the class String
,. This methods do not change characters in place, but return a new string.
Create a new string letter by letter:
String newString = new String();
for(int i=0; i < originalText.length(); i++) {
if (Character.isUpperCase(originalText.charAt(i))) {
newString += originalText.substring(i, i+1).toLowerCase();
} else {
newString += originalText.substring(i, i+1).toUpperCase();
}
}
Or alternatively
String newString = new String();
for(int i=0; i < originalText.length(); i++) {
char ch = originalText.charAt(i);
if (Character.isUpperCase(ch)) {
newString += Character.toLowerCase(ch);
} else {
newString += Character.toUpperCase(ch);
}
}