Search code examples
javastringcharuppercaselowercase

Convert characters of a string to opposite case


//HERE WHY IS IT CONVERTING TO LOWER CASE BUT NOT TO UPPER CASE

public class LowerUpperCase {
    
    public static void main(String[] args) {
        String s="lowerUppercase";
       
        
        
        for (int i = 0; i < s.length()-1; i++) {

            if(s.charAt(i) >='a' && s.charAt(i)<='z'){  //OR IF DONE THIS NOT WORKING
```
   if((s.charAt(i) >='a' && s.charAt(i)<='z' ) || (s.charAt(i) >='A' && s.charAt(i)<='Z')){
```

               
                 s=s.toLowerCase();//here should i go for 

            }
            else if(s.charAt(i) >='A' && s.charAt(i)<='Z'){
               
                s=s.toUpperCase();

           }
           
            
        }
        System.out.println(s);
    }
}

//I ALWAYS GET OUTPUT LIKE loweruppercase or LOWERUPPERCASE

INPUT:LowerUpperCase
OUTPUT:lOWERuPPERcASE  expected

HERE WHY IS IT CONVERTING TO LOWER CASE BUT NOT TO UPPER CASE 

I ALWAYS GET OUTPUT LIKE loweruppercase or LOWERUPPERCASE

Solution

  • Your code seems on the righ track, but you need to toggle between both lower and upper case. Try this version:

    String s = "lowerUppercase";
    StringBuilder output = new StringBuilder();
    
    for (int i=0; i < s.length(); i++) {
        if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
            output.append(Character.toUpperCase(s.charAt(i)));
        }
        else {
            output.append(Character.toLowerCase(s.charAt(i)));
        }
    }
    
    System.out.println(output.toString());
    // LOWERuPPERCASE
    

    Note that the above assumes that you would only have lower and upper case English alphabet letters in the input string. If not, then the answer might have to change.