简体   繁体   中英

StringIndexOutOFBoundsException: 0

I am a relative beginner to Java and am having an issue with a user controlled do-while loop that accepts user input to repeat. Here is the code at the end of the loop.

System.out.print("Do you wish to continue? (Y for yes " +
                            "/ N for no)");
        input = keyboard.nextLine();
        input.length();
        repeat = input.charAt(0);

        }while (repeat == 'Y' | repeat == 'y');

I know it's throwing the exception because of the value, but can't figure out what to do to fix it, as I'm sure it's relatively simple. Thanks for the help.

Edit 1: Stacktrace:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
String index out of range: 0 
at java.lang.String.charAt(Unknown Source) 
at FractionTest.main(FractionTest.java:59)

It looks like you read empty line which returned you empty string "" so there is no characters there (not even 0th).

It usually happens when you are using nextLine right after other nextABC methods like nextInt since such methods doesn't consume line separators, and nextLine reads text until next line separator (or end of stream).

In that case you can add nextLine after that nextInt to consume line separator.

Anyway to avoid reading character from empty string and exception you can use something like

} while (input.toLowerCase().startsWith("y"));

instead of

    input.length();//this actually doesn't change anything, you can remove it
    repeat = input.charAt(0);

} while (repeat == 'Y' | repeat == 'y');

As @Phesmo mentioned you may be getting a 0-length line. This is an obscure problem. Have you called nextInt() , nextLong() , nextShort() , nextByte() , or nextBoolean() on the Scanner before calling nextLine() ?


Try this

System.out.print("Do you wish to continue? (Y for yes / N for no)");

char ans;
do {
   ans = keyboard.next().charAt(0);
   // filter input
} while (ans == 'Y' || ans == 'y' || ans == 'N' || ans == 'n');

repeat = ans;

} while (repeat == 'Y' | repeat == 'y');

From documentation :

String Scanner#next()
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

Or this

System.out.print("Do you wish to continue? (Y for yes / N for no)");    
repeat = keyboard.next("[YyNn]").charAt(0);

} while (repeat == 'Y' | repeat == 'y');

From documentation :

String Scanner#next(String pattern)
Returns the next token if it matches the pattern constructed from the specified string.

"[YyNn]" is a character class pattern, it means match any character from the set .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM