数组错误java.lang.ArrayIndexOutOfBoundsException
我对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();
}
应该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。 – 2013-03-27 17:57:41
仍然不会走出索引 – Ankit 2013-03-27 17:58:35
它不回答他的问题。大小为0的数组在索引0处没有元素。 – 2013-03-27 17:59:01
for(counter = 0; counter <= trips; counter++)
将其更改为:
for(counter = 0; counter < trips; counter++)
您gallons
数组的大小是trips
。由于第一指标与0
方式启动gallons
阵列的最后一个索引将会显示是trips-1
。而在你的代码,你想在指数trips
时访问元素(反== TRIPS)在for循环为真,这导致ArrayIndexOutOfBounException
是的,请记住,数组从0开始,而不是1,所以如果你想迭代10个元素的数组,你需要从0到9 – jsedano 2013-03-27 17:57:39
更改此
counter <= trips
这个
counter < trips
在for
构造那里。
尝试此
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();
}
}
变化
for(counter = 0; counter <= trips; counter++)
到
for(counter = 0; counter < trips; counter++)
数组的索引从0开始(长度-1)
是什么的初始值'trips'? – 2013-03-27 17:57:00
'柜台将修复 – 2013-03-27 17:57:43
也不要忘记初始化加仑。 – fvu 2013-03-27 18:00:10