public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String word, end;
    int length = 1; //length of int is determined here so it can be incremented in loop

    System.out.println("Enter a word: ");
    word = scan.next();
    while (1 == 1) {
    end = word.substring  (word.length()-length); 
    System.out.print (end +  " ");

    length = length + 1; //variable length is incremented so after loop 2 chars from the end will be printed, then 3 and so on until none are left.

      if (word == null) {

I am trying to achieve the following i.e. if "JAVA" was typed in what would return is "A VA AVA JAVA". although that is returned I keep getting the following error and have tried about everything I can to fix it but none of them work. Is there any easier method I can use or if a little modification on the above code will fix the problem, please inform me!

"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1"

5 Years
Discussion Span
Last Post by asif49

The problem is in line 10 where you keep the while loop going on forever. Even though it is possible to do it, it does not make sense at all to do it in your case. And because the loop keeps going on, finally your 'length' value will be greater than the word.length() value. As a result, in line 11, you will get the index out of range which is equal to -1 when length is greater than word.length(). What you need to do is to use your 'length' for checking the condition in the while loop instead. If the length is still less than or equal to the word.length(), then keep going...

Also, lines 16-18 do nothing for your program... The Scanner should not return null when you use next() from console input...

Edited by Taywin: n/a


YES! thank you so much for your help i didn't think people would just be willing to help for nothing in return but it's greatly appreciated, problem fixed :)

and lines 16 - 18 was just a neccessity for the assignment i need to do this for.

Thank you very much though!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.