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