Why am I getting StringIndexOutOfBoundsException in this code?

别来无恙 提交于 2019-12-25 04:17:50

问题


I am getting the following error message in Java

Exception in thread "main" 

    java.lang.StringIndexOutOfBoundsException: String index out of range: 0

Here is my code -

public static void main(String[] args) {

    double gissade = 70;
    int input;
    java.util.Scanner in = new java.util.Scanner(System.in);

    char spelaIgen = 'j';
    // char input2;

    int antal = 1;

    while (spelaIgen == 'j') {
        System.out.print("gissa ett number?");
        Input = in.nextInt();

        if (input < gissade) {
            System.out.println("du har gissat för lågt försök igen");
            antal++;
        } else if (input > gissade) {
            System.out.println("du har gissat för högt försök igen");

            antal++;
        }
        if (input == gissade) {
            System.out.println("du har gissat rätt");
            System.out.println("efter " + antal + " försök");
        }

        System.out.println("vill du försöka igen? j/n");
        char input2 = in.nextLine().charAt(0);
        // String s1=in.nextLine();
        // char c1=s1.charAt(0);

        // if (input=='n');
        // System.exit(0);

    }
}

回答1:


This is because nextInt() won't consume the newLine, so you get an empty string when you try to do the readLine(), and try to perform

"".charAt(0);

which throws your Exception.

Try adding an extra nextLine() after your nextInt().

A good practice is to always use nextLine(), and then parse the string you get. To get your int for example, you could do like this:

String intInput;
do {
  System.out.print("gissa ett nummer?");
  intInput = in.nextLine();
while(!intInput.matches("\\d+"));
int number = Integer.parseInt(intInput);

This will repeat until you enter a valid number.



来源:https://stackoverflow.com/questions/11541415/why-am-i-getting-stringindexoutofboundsexception-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!