我是编码新手,我需要一些帮助来完成这项任务。无论我尝试什么,我都会不断收到“ArrayIndexOutOfBoundsException”。我可以让程序运行,直到我输入最后一个击球平均值,然后我收到错误。
预计将进入 8 个击球平均值,例如 .250、.302 等
这是确切的错误消息。 “线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8 在 BattingAverage.main(BattingAverage.java:38)"
提前感谢您的帮助!
import java.util.Scanner;
public class BattingAverage
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
// Declare a named constant for array size here.
final int MAX_AVERAGES = 8;
// Declare array here.
double averages[] = new double[MAX_AVERAGES];
// Use this integer variable as your loop index.
int loopIndex;
// Use this variable to store the batting average input by user.
double battingAverage = 0;
// String version of batting average input by user.
String averageString;
// Use these variables to store the minimim and maximum batting averages.
double min, max;
// Use these variables to store the total and the average.
double total, average;
// Write a loop to get batting averages from user and assign to array.
for(loopIndex = 0; loopIndex < MAX_AVERAGES; loopIndex++)
{
System.out.println("Enter a batting average: ");
averageString = s.nextLine();
battingAverage = Double.parseDouble(averageString);
}
// Assign value to array.
averages[loopIndex] = battingAverage;
// Assign the first element in the array to be the minimum and the maximum.
min = averages[0];
max = averages[0];
// Start out your total with the value of the first element in the array.
total = averages[0];
// Write a loop here to access array values starting with averages[1]
for(loopIndex = 1; loopIndex<MAX_AVERAGES; loopIndex++)
{
// Within the loop test for minimum and maximum batting averages.
if(averages[loopIndex]<min)
min = averages[loopIndex];
if(averages[loopIndex]>max)
max = averages[loopIndex];
// Also accumulate a total of all batting averages.
total += averages[loopIndex];
}
// Calculate the average of the 8 averages.
average = total/ MAX_AVERAGES;
// Print the averages stored in the averages array.
for(loopIndex = 0; loopIndex<MAX_AVERAGES; loopIndex++)
{
System.out.println("averages" + averages[loopIndex]);
}
// Print the maximum batting average, minimum batting average, and average batting average.
System.out.println("Minimum batting average is: " + min);
System.out.println("Maximum batting average is: " + max);
System.out.println("Average batting average is: " + average);
System.exit(0);
}
}
答案 0 :(得分:0)
这里
advertised.listeners=PLAINTEXT://152.255.215.185:9092
zookeeper.connect=152.255.215.185:2181
在循环结束时 // Write a loop to get batting averages from user and assign to array.
for(loopIndex = 0; loopIndex < MAX_AVERAGES; loopIndex++)
{
System.out.println("Enter a batting average: ");
averageString = s.nextLine();
battingAverage = Double.parseDouble(averageString);
}
// Assign value to array.
averages[loopIndex] = battingAverage;
在检查退出条件 loopIndex
之前递增,因此在最后一个循环之后 loopIndex < MAX_AVERAGES
等于 loopIndex
。
尝试访问 MAX_AVERAGES
数组的索引(因为最后一个有效索引是 averages
)会引发异常。