数组错误java.lang.ArrayIndexOutOfBoundsException

时间:2013-03-27 17:55:18

标签: java arrays

我是Java的新手,目前正在学习数组。 所以我正在制作这个小程序来输入使用的气体和行驶里程来计算每加仑英里数,但每当我运行程序时,我在第21行得到一个错误(英里[计数器] = input.nextInt();)错误说:

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

5 个答案:

答案 0 :(得分: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();
}

}

答案 1 :(得分:0)

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

将其更改为:

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

gallons数组的大小为trips。由于第一个索引以0开头,因此gallons数组的最后一个索引将为trips-1 。并且在您的代码中,当for循环中的(counter == trips)变为true时,您尝试访问索引trips处的元素,这导致ArrayIndexOutOfBounException

答案 2 :(得分:0)

更改此

counter <= trips

到这个

counter < trips

for构造中。

答案 3 :(得分: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();
    }   
}

答案 4 :(得分:0)

更改

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

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

数组索引从0开始到(长度-1)