1

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();
     }
  }
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
glow
  • 21
  • 3
  • Please read [ask]. The title of your question should be a consist description of the problem - not your skill level. The tags you apply to your question should be *relevant*. You seem to be writing Java, not using the processing language or toupper/tolower which are C++ tags. – Quentin Dec 11 '21 at 12:42

1 Answers1

2

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);
   } 
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174