1

我对 Java 很陌生,目前正在学习数组。所以我正在制作这个小程序来输入使用的汽油和行驶的英里数来计算每加仑英里数,但是每当我运行该程序时,我都会在第 21 行得到一个错误(miles [counter] = 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();
}
4

5 回答 5

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

}

于 2013-03-27T17:56:07.067 回答
0

改变

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

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

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

于 2013-03-27T17:58:07.767 回答
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();
    }   
}
于 2013-03-27T17:57:10.653 回答
0
for(counter = 0; counter <= trips; counter++)

将其更改为:

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

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

于 2013-03-27T17:56:07.240 回答
0

改变这个

counter <= trips

对此

counter < trips

在那里的for构造中。

于 2013-03-27T17:56:29.363 回答