我對Java很新,當前正在學習數組。 所以我做了這個小程序輸入使用的燃氣和行駛里程計算每加侖英里數,但是每當我運行該程序時,我都會收到第21行的錯誤(英里[counter] = input.nextInt();)錯誤提示:數組錯誤java.lang.ArrayIndexOutOfBoundsException
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at GasMileage.inputGasAndMiles(GasMileage.java:21)
at GasMileage.main(GasMileage.java:44)
我不知道這是什麼意思我也不知道如何解決它,這將會是巨大的,如果我能得到這方面的一些幫助。
int counter = 0;
int[] gallons, miles = new int[trips];
public void inputGasAndMiles(){
for(counter = 0; counter <= trips; counter++){
System.out.print("\nInput miles traveled: ");
miles[counter] = input.nextInt();
System.out.print("Input gallons of fuel used: ");
gallons[counter] = input.nextInt();
}
}
編輯
public void askTrips(){
System.out.print("How many trips would you like to calculate for: ");
trips = input.nextInt();
}
堆棧跟蹤:
public static void main(String[]args){
GasMileage gas = new GasMileage();
gas.askTrips();
gas.inputGasAndMiles();
gas.calculate();
gas.display();
}
是什麼的初始值'trips'? – 2013-03-27 17:57:00
'櫃檯<旅行>將修復 – 2013-03-27 17:57:43
也不要忘記初始化加侖。 – fvu 2013-03-27 18:00:10