Search code examples
javastringuppercaselowercase

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters


Alternately display any text that is typed in the textbox

//     in either Capital or lowercase depending on the original
//     letter changed.  For example:  CoMpUtEr will convert to
//     cOmPuTeR and vice versa.
    Switch.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e )

            String characters = (SecondTextField.getText()); //String to read the user input
            int length = characters.length();  //change the string characters to length

         for(int i = 0; i < length; i++)  //to check the characters of string..
         {             
            char character = characters.charAt(i);          

            if(Character.isUpperCase(character)) 
            {
                SecondTextField.setText("" + characters.toLowerCase());

            }
            else  if(Character.isLowerCase(character))
            {
                 SecondTextField.setText("" + characters.toUpperCase()); //problem is here, how can i track the character which i already change above, means lowerCase**
                }               
         }}     
    });

Solution

  • setText is changing the text content to exactly what you give it, not appending it.

    Convert the String from the field first, then apply it directly...

    String value = "This Is A Test";
    StringBuilder sb = new StringBuilder(value);
    for (int index = 0; index < sb.length(); index++) {
        char c = sb.charAt(index);
        if (Character.isLowerCase(c)) {
            sb.setCharAt(index, Character.toUpperCase(c));
        } else {
            sb.setCharAt(index, Character.toLowerCase(c));
        }
    }
    
    SecondTextField.setText(sb.toString());