2013-03-27 39 views
1

我對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(); 
} 
+0

是什麼的初始值'trips'? – 2013-03-27 17:57:00

+0

'櫃檯<旅行>將修復 – 2013-03-27 17:57:43

+0

也不要忘記初始化加侖。 – fvu 2013-03-27 18:00:10

回答

3

應該for (counter = 0; counter < trips; counter++)

,因爲數組索引從零開始,所以最大的索引將(size-1)size

編輯:

int trips= 0; //any +ve value 
int[] gallons = new int[trips], 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(); 
} 

}

+0

這不提供相同的錯誤。 '旅行'最有可能是0,導致指數超出範圍0。 – 2013-03-27 17:57:41

+0

仍然不會走出索引 – Ankit 2013-03-27 17:58:35

+0

它不回答他的問題。大小爲0的數組在索引0處沒有元素。 – 2013-03-27 17:59:01

0
for(counter = 0; counter <= trips; counter++) 

將其更改爲:

for(counter = 0; counter < trips; counter++) 

gallons數組的大小是trips。由於第一指標與0方式啓動gallons陣列的最後一個索引將會顯示是trips-1。而在你的代碼,你想在指數trips時訪問元素(反== TRIPS)在for循環爲真,這導致ArrayIndexOutOfBounException

+0

是的,請記住,數組從0開始,而不是1,所以如果你想迭代10個元素的數組,你需要從0到9 – jsedano 2013-03-27 17:57:39

0

更改此

counter <= trips 

這個

counter < trips 

for構造那裏。

0

嘗試此

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(); 
    } 
} 
0

變化

for(counter = 0; counter <= trips; counter++) 

for(counter = 0; counter < trips; counter++) 

數組的索引從0開始(長度-1)

相關問題