-3

我正在尝试获取用户输入并从最后一个字符开始打印单词,并将前一个字符添加到下一行,前面少一个空格,看起来它与右侧对齐。

但它显示存在错误: System.out.print(word.charAt(count));

Scanner input = new Scanner(System.in);
System.out.print("Enter word to print: ");
String word = input.nextLine();
System.out.println();

int line, space, count = -1;

for (line = word.length(); line > 0; line--){

  for (space = line; space > 0; space--){
    System.out.print(" ");
    count++;
    }

  for ( ; count <= word.length(); count++){
    System.out.print(word.charAt(count));
  }

System.out.println();
}

错误显示为:

Exception in thread "main java.lang.String.IndexOutOfBoundsException: S
at java.lang.String.charAt(String.java:658)
at HelloWorld.main(HelloWorld.java:22)
4

1 回答 1

1

问题出在你的最后一个for循环中。count <= word.length()意味着只要count不超过word.length(),循环就会继续运行,这是一个问题,因为 a 中每个字符的索引String从 0 开始,而不是 1。

因此,例如,如果您输入一个五个字母的单词,for循环将一直运行直到count等于 5。在其最后一次迭代中,当count等于 5 时,它会抛出一个,IndexOutOfBoundsException因为word只上升到索引 4(第一个字符0在第二个是 at 1,依此类推,这意味着第五个字符在 index 4)。

for因此,该循环的退出条件count <= word.length()应该是,而不是count < word.length()

于 2015-10-30T03:21:55.997 回答