-3

I'm trying to get a user input and print the word starting from the last character and adding the previous one to the next line with one less space in the front, looking like it's aligned to the right.

but it shows there's an error in: 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();
}

error shows as:

Exception in thread "main java.lang.String.IndexOutOfBoundsException: S
at java.lang.String.charAt(String.java:658)
at HelloWorld.main(HelloWorld.java:22)
Doraemon
  • 11
  • 1
  • 3

1 Answers1

1

The problem is in your last for loop. count <= word.length() means that the loop will continue to run as long as count does not exceed word.length(), which is a problem because the index for each character in a String starts as 0, not 1.

So, for instance, if you enter a five-letter word, the for loop will run until count equals 5. On its final iteration, when count is equal to 5, it throws an IndexOutOfBoundsException because word only goes up to index 4 (the first character is at 0, the second is at 1, and so on, meaning the fifth character is at index 4).

So, instead of the exit condition for that for loop being count <= word.length(), it should be count < word.length().

Bethany Louise
  • 646
  • 7
  • 13