當我運行下面的程序,我得到在第20行的錯誤,這是我的代碼:Java的ArrayIndexOutOfBoundsException異常錯誤
package J1;
import java.util.Scanner;
public class SpeedLimit {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
String[] tab = new String[2];
String output="";
int speed = 0;
while(input!=-1){
int last =0;
for (int i=0; i<input ; i++){
String pair = keyboard.next();
tab = pair.split(" ");
speed = speed + Integer.parseInt(tab[0])*(Integer.parseInt(tab[1])-last);
last = Integer.parseInt(tab[1]);
}
output = output +speed + "miles" + "\n";
speed =0;
input = Integer.parseInt(keyboard.nextLine());
}
System.out.println(output);
}
}
當我運行的代碼,我從鍵盤輸入下列輸入:
3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1
得到這個結果作爲輸出: 170英里 180英里 90英里
但我GE T,則下面錯誤,當我運行的代碼
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at J1.SpeedLimit.main(SpeedLimit.java:20)
'字符串對= keyboard.nextLine();' –
我不理解 –
在'String pair = keyboard.next();'.next()'返回「這個掃描器的下一個完整標記。」我認爲@SanketMakani建議它可能只返回第一個單詞而不是整行。如果你用建議的替換這條線,它將獲取整條線。 – dolan