-3

ユーザー入力を取得して、最後の文字から始まる単語を出力し、前の文字を次の行に追加して、前のスペースを1つ減らして、右に配置されているように見せようとしています。

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()限りループが実行され続けることを意味します。これは、 a の各文字のインデックスが1 ではなく 0 から始まるため、問題です。countword.length()String

したがって、たとえば、5 文字の単語を入力すると、forループはcount5 に等しくなるまで実行されます。最後の反復で、が 5 に等しい場合、インデックス 4 までしか移動しないためcount、がスローされます (最初の文字は, にあります)。 2番目の文字は at などであり、5 番目の文字は index にあることを意味します)。IndexOutOfBoundsExceptionword014

forしたがって、そのループの終了条件は ではなくcount <= word.length()、 である必要がありますcount < word.length()

于 2015-10-30T03:21:55.997 に答える