Java:StringBuilder setCharAt无法正常工作

时间:2016-04-15 14:19:23

标签: java stringbuilder

所以我正在编写一个程序,其中每个字母的大小写都是颠倒的。如果输入“Hello”,则输出“hELLO”。我知道无论我做什么都不会起作用,但我还不完全明白为什么它不起作用。

  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);
  }

1 个答案:

答案 0 :(得分:3)

它确实有效,但最后你在变量phrase中打印原始字符串,你可能想要在变量aWord中打印转换后的字符串。