问题
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