0

So I'm making a program where the case of each letter is inverted. If you enter "Hello", it outputs "hELLO". I'm aware that whatever I'm doing is not going to work, but I'm just not totally clear on WHY it won't work.

  public static void main(String [] args){

  Scanner keyboard = new Scanner(System.in);
  keyboard.useDelimiter(System.getProperty("line.separator"));
  char letter;
  char newLetter;

  String strLetter;
  System.out.print("Phrase: ");
  String phrase = keyboard.next();
  StringBuilder aWord = new StringBuilder(phrase);
  int wordLength = phrase.length();

  //loop through each letter
  for (int x = 0; x < wordLength; x++) {
     letter = phrase.charAt(x);

     //if letter is uppercase, set newLetter to lowercase and vice versa.
     if (Character.isUpperCase(letter)) {
        newLetter = Character.toLowerCase(letter);
     } else {
        newLetter = Character.toUpperCase(letter);
     }
     //When I print new letter here, it shows as the updated version
     //However, setCharAt is not actually updating, as seen by 
     //the "System.out.print(phrase);" line outside of the loop.
     aWord.setCharAt(x,newLetter);
     System.out.print(newLetter);
  }

  System.out.println();
  System.out.print(phrase);
  }
user230250
  • 131
  • 1
  • 10
  • 1
    So you are building `aWord` but never printing it. So how do you know that setCharAt is not working? – ControlAltDel Apr 15 '16 at 14:23
  • Isn't it easier to use [WordUtils#swapCase](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#swapCase(java.lang.String))? – Sergii Bishyr Apr 15 '16 at 14:24

1 Answers1

3

It does work, but at the end you are printing the original string in variable phrase and you probably want to print the converted string in variable aWord.

wero
  • 32,544
  • 3
  • 59
  • 84