9

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**
                }               
         }}     
    });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
akki0996
  • 713
  • 2
  • 6
  • 14
  • 2
    you have an `else`, so if it starts as upper case it won't go through the 2nd branch of the `if`. If it starts as lower case it will go through the second branch (and not the first) - what problem are you actually having? – John3136 Feb 20 '13 at 03:59
  • agreed. Looks like it should be working already – Memento Mori Feb 20 '13 at 04:00
  • Oh I see the problem.. Don't set characters.toUpperCase() or similar. Only change one character at a time. Your loop is already set up to do it that way, but you're changing the whole string's case. – Memento Mori Feb 20 '13 at 04:01

16 Answers16

16

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());
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
5

You don't have to track whether you've already changed the character from upper to lower. Your code is already doing that since it's basically:

1   for each character x:
2       if x is uppercase:
3           convert x to lowercase
4       else:
5           if x is lowercase:
6                convert x to uppercase.

The fact that you have that else in there (on line 4) means that a character that was initially uppercase will never be checked in the second if statement (on line 5).

Example, start with A. Because that's uppercase, it will be converted to lowercase on line 3 and then you'll go back up to line 1 for the next character.

If you start with z, the if on line 2 will send you directly to line 5 where it will be converted to uppercase. Anything that's neither upper nor lowercase will fail both if statements and therefore remain untouched.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
4

You can use StringUtils.swapCase() from org.apache.commons

Pshemo
  • 122,468
  • 25
  • 185
  • 269
4

This is a better method :-

void main()throws IOException
{
    System.out.println("Enter sentence");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String str = br.readLine();
    String sentence = "";
    for(int i=0;i<str.length();i++)
    {
        if(Character.isUpperCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)+32);
            sentence = sentence + ch2;
        }
        else if(Character.isLowerCase(str.charAt(i))==true)
        {
            char ch2= (char)(str.charAt(i)-32);
            sentence = sentence + ch2;
        }
        else
        sentence= sentence + str.charAt(i);

    }
    System.out.println(sentence);
}
Shubham
  • 310
  • 4
  • 16
3

The problem is that you are trying to set the value of SecondTextField after checking every single character in the original string. You should do the conversion "on the side", one character at a time, and only then set the result into the SecondTextField.

As you go through the original string, start composing the output from an empty string. Keep appending the character in the opposite case until you run out of characters. Once the output is ready, set it into SecondTextField.

You can make an output a String, set it to an empty string "", and append characters to it as you go. This will work, but that is an inefficient approach. A better approach would be using a StringBuilder class, which lets you change the string without throwing away the whole thing.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2
String name = "Vikash";
String upperCase = name.toUpperCase();
String lowerCase = name.toLowerCase();
Antares42
  • 1,406
  • 1
  • 15
  • 45
rocks
  • 49
  • 3
  • 6
    Please don't simply post the code. Give some explanation or information or usage about your code. For example, see [this answer](http://stackoverflow.com/a/16893057/756941). – Nazik Jan 29 '14 at 05:50
2

This is a better approach without using any String function.

public static String ReverseCases(String str) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
      char temp;
      if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
        temp = (char)(str.charAt(i) - 32);
      }
      else if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
        temp = (char)(str.charAt(i) + 32);
      }
      else {
        temp = str.charAt(i);
      }

      sb.append(temp);
    }
    return sb.toString();
  }
Amarjit Datta
  • 251
  • 2
  • 7
1

Here you are some other version:

public class Palindrom {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a word to check: ");
    String checkWord = sc.nextLine();
    System.out.println(isPalindrome(checkWord));
    sc.close();

}

public static boolean isPalindrome(String str) {        
    StringBuilder secondSB = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    sb.append(str);
    for(int i = 0; i<sb.length();i++){
        char c = sb.charAt(i);
        if(Character.isUpperCase(c)){
            sb.setCharAt(i, Character.toLowerCase(c));
        }
    }
    secondSB.append(sb);
    return sb.toString().equals(secondSB.reverse().toString());
}

}

Tano
  • 609
  • 8
  • 23
1
StringBuilder b = new StringBuilder();

Scanner s = new Scanner(System.in);
String n = s.nextLine();

for(int i = 0; i < n.length(); i++) {
    char c = n.charAt(i);

    if(Character.isLowerCase(c) == true) {
        b.append(String.valueOf(c).toUpperCase());
    }
    else {
        b.append(String.valueOf(c).toLowerCase());
    }
}

System.out.println(b);
Akira
  • 4,385
  • 3
  • 24
  • 46
1

Methods description:

*toLowerCase()* Returns a new string with all characters converted to lowercase.

*toUpperCase()* Returns a new string with all characters converted to uppercase.

For example:

"Welcome".toLowerCase() returns a new string, welcome

"Welcome".toUpperCase() returns a new string, WELCOME

Bulat
  • 720
  • 7
  • 15
1

If you look at characters a-z, you'll see that all of them have the 6th bit is set to 1. Where in A-Z 6th bit is not set.

A = 1000001    a = 1100001
B = 1000010    b = 1100010
C = 1000011    c = 1100011
D = 1000100    d = 1100100     
...
Z = 1011010    z = 1111010

So all we need to do is to iterate through each character from a given string and then do XOR(^) with 32. In this way, the 6th bit can swap.

Look at the below code for simply changing the string case without using any if-else conditions.

public final class ChangeStringCase {
    public static void main(String[] args) {
        String str = "Hello World";
        for (int i = 0; i < str.length(); i++) {
            char ans = (char)(str.charAt(i) ^ 32);
            System.out.print(ans); // Final Output: hELLO wORLD
        }
    }
}

Time Complexity: O(N) where N = Length of the string.

Space Complexity: O(1)

0
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String satr=scanner.nextLine();
    String newString = "";
    for (int i = 0; i < satr.length(); i++) {
        if (Character.isUpperCase(satr.charAt(i))) {
            newString+=Character.toLowerCase(satr.charAt(i));
        }else newString += Character.toUpperCase(satr.charAt(i));
    }
    System.out.println(newString);
}
Umarjon
  • 11
  • Hi Umarjon, on future answers try to add a short explanation on your answer that will help the user that posted the question to understand your solution and learn from at – Lupin Apr 19 '15 at 06:31
0
public class Toggle {
public static String toggle(String s) {
    char[] ch = s.toCharArray();

    for (int i = 0; i < s.length(); i++) {
        char charat = ch[i];
        if (Character.isUpperCase(charat)) {
            charat = Character.toLowerCase(charat);
        } else
            charat = Character.toUpperCase(charat);
        System.out.print(charat);
    }
    return s;
  }

public static void main(String[] args) {
    toggle("DivYa");
   }
  }
Divya
  • 1
  • 1
  • 1
    Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Feb 10 '17 at 10:38
0
import java.util.Scanner;
class TestClass {
    public static void main(String args[]) throws Exception {
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            if (Character.isUpperCase(ch[i])) {
                ch[i] = Character.toLowerCase(ch[i]);
            } else {
                ch[i] = Character.toUpperCase(ch[i]);
            }
        }
        System.out.println(ch);
    }
}
J-Alex
  • 6,881
  • 10
  • 46
  • 64
Aditya Parmar
  • 1,139
  • 13
  • 22
0
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
    public class ChangeCase {
        public static void main(String[]args) {

            String input;
            Scanner sc= new Scanner(System.in);
                System.out.println("Enter Letter from upper case");
                input=sc.next();

            String result;
            result= input.toLowerCase();
            System.out.println(result);
        }
    }
-1
    String str1,str2;
    Scanner S=new Scanner(System.in);
    str1=S.nextLine();
    System.out.println(str1);
    str2=S.nextLine();
    str1=str1.concat(str2);
    System.out.println(str1.toLowerCase()); 
Padma
  • 17
  • 2