[英]Why am I getting this StringIndexOutOfBoundsException on executing code?
[英]Why am I getting StringIndexOutOfBoundsException in this code?
我在Java中收到以下錯誤消息
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
這是我的代碼-
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);
}
}
這是因為nextInt()
不會消耗newLine,因此當您嘗試執行readLine()
並嘗試執行時,會得到一個空字符串
"".charAt(0);
這會引發您的異常。
嘗試在nextInt()
之后添加一個額外的nextLine()
nextInt()
。
一個好的做法是始終使用nextLine()
,然后解析得到的字符串。 例如,要獲取您的int
,可以執行以下操作:
String intInput;
do {
System.out.print("gissa ett nummer?");
intInput = in.nextLine();
while(!intInput.matches("\\d+"));
int number = Integer.parseInt(intInput);
重復此過程,直到您輸入有效的數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.