任务(不做作业):编写一个程序,读取未指定数量的分数,并确定有多少分数高于或等于平均分数以及有多少分数低于平均分数 问题:在尝试计算输入分数的出现时,我一直得到数组索引超出范围的错误。非常感谢您就如何改善发生输出提供指导。
import java.util.Scanner;
public class AnalyseScore {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
System.out.println("Enter the number of students:");
int studentnumber = input.nextInt();
//creat array
int [] scores =new int[studentnumber];
int sum =0;
System.out.println("Enter the student scores:");
for(int i =0; i<scores.length;i++){
scores[i]= input.nextInt();
}
//calculate the sum and the average
double average;
for(int i =0; i<scores.length;i++){
sum +=scores[i];
}
average = sum/studentnumber;
System.out.println("The average is:" + (int)(average*100)/100.0);
int belowavg=0;
int aboveavg=0;
for(int i=0;i<scores.length;i++){
if (scores[i]>average)
aboveavg++;
else
belowavg++;
}
System.out.println(" the number of scores bove the average:"+ aboveavg);
System.out.println("the number of scores below average:" + belowavg);
int [] count= new int[scores.length];
for( int i=0;i<scores.length;i++){
count[scores[i]]++;
System.out.println(scores[i] + "occured" + count[i]);
}
}
}
答案 0 :(得分:1)
int [] count= new int[scores.length];
for( int i=0;i<scores.length;i++){
count[scores[i]]++;
此处count
的索引受scores[i]
限制,可能大于scores.length
。
如果已知scores
有界,您可以计算最大值并分配足够的大小;否则,使用Map<Integer, Integer>
或TreeMap<Integer, Integer>
等HashMap<Integer, Integer>
可能会更好。
如果您拒绝使用Map
,我建议您排序并计算scores
。
if (scores.length > 0) {
Arrays.sort(scores);
int count = 1;
int prevscore = scores[0];
for (int i = 1; i <scores.length; ++i) {
if (scores[i] == prevscore) {
++count;
} else {
System.out.println(prevscore + " occured " + count);
count = 1;
prevscore = scores[i];
}
}
System.out.println(prevscore + " occured " + count);
}
答案 1 :(得分:1)
直到最后一步,你的代码看起来还不错。您正在尝试计算每个分数的出现次数,但这需要count
数组的长度为最大分数(这在空间方面效率非常低)。事实上,你并没有让count
足够大,因此你的错误。考虑使用HashMap<Integer,Integer>
而不是数组来计算。此映射中的键是分数,值是出现次数:
HashMap<Integer, Integer> count = new HashMap<>();
for(int i=0;i<scores.length;i++){
if(! count.containsKey(scores[i]) count.put(scores[i], 1); //New score, has been seen once
else count.put(scores[i], count.get(scores[i]) + 1); //Already seen score, inc count.
}
答案 2 :(得分:0)
计数的长度等于得分的长度。您收到错误,因为最高得分高于得分的长度。