这是我的代码:包project4;
import java.util.Scanner;
公共类ScoreAnalyzer {
//#OfScores is the length of the scores array
public static int numberOfScores = 0;
public static double[] scores = new double[numberOfScores];
public static double sum = 0.0;
public static double place = 0.0;
//Of sorted list
public static double[] sortedList = new double[numberOfScores];
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of scores you'd like to average: ");
numberOfScores = input.nextInt();
scores = new double[numberOfScores];
for (int count = 0; count < scores.length; count++) {
System.out.print("Enter score #" + count + ": ");
place = input.nextDouble();
scores[count] = place;
System.out.println("The score of " + scores[count] + " is " + getGrade(count));
}
sumOfScores();
System.out.println("The average of these scores is: " + averageOfScores());
sort();
System.out.println("The sorted list of scores (above average scores are "
+ "marked with an\n" + "asterisk '*'): " + sortedList[numberOfScores]);
}
public static char getGrade(int i) {
//this
if (scores[i] >= 90.0) {
return 'A';
}
if (scores[i] >= 80.0) {
return 'B';
}
if (scores[i] >= 70.0) {
return 'C';
}
if (scores[i] >= 60.0) {
return 'D';
}
else {
return 'F';
}
}
public static double sumOfScores() {
//sum = 0.0;
for (int i = 0; i < numberOfScores; i++) {
sum += scores[i];
}
return sum;
}
public static double averageOfScores() {
double average = sum / numberOfScores;
return average;
}
public static void sort() {
for (int i = 0; i < scores.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMin = scores[i];
int currentMinIndex;
currentMinIndex = i;
for (int j = i + 1; j < scores.length; j++) {
if (currentMin > scores[j]) {
currentMin = scores[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) {
sortedList[currentMinIndex] = scores[i];
scores[i] = currentMin;
}
}
}
}
该程序的目的是提示用户输入首先要输入的分数,然后允许用户输入该分数。输入每个分数后,程序应为他们输入的每个分数给一个分数。然后,程序应使用一种方法来求和,并将该和传递到一种方法中以求平均值,并对方法中的数组进行排序。应将排序后的数组与平均值一起显示,并且每个高于平均值的分数都应显示注意旁边带有星号。
[运行程序时,我可以输入要平均的分数数量,输入这些分数,获得总和和平均数,但是在对它进行排序以使星号高于平均数时遇到了问题:
输入您想要平均的分数数量:3
输入得分#0:90
90.0的分数是A
输入得分#1:80
[80.0分是B
输入得分#2:70
[70.0分是C
这些分数的平均值是:80.0
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:2
at project4.ScoreAnalyzer.sort(ScoreAnalyzer.java:86)
at project4.ScoreAnalyzer.main(ScoreAnalyzer.java:32)
问题出在您的for
循环上。由于数组索引以0开头,因此对于大小为3的数组,最高索引将上升为2。但是,按照您的for循环,它的索引将上升为3,这就是ArrayOutOfBoundsException的原因。如下使用它:
for (int count = 0; count < scores.length ; count++)