正确打印中位数,平均值和模式时遇到问题。所需要的只是一些移动编码和一些数字/单词更改!!
程序:
public static int StudentAverage(int [] array)
//almost there, some random big code is in front of the wording?
{
int avg;
int sum=0;
for(int i=0;i<4;i++){
sum=sum+array[i];
}
avg=sum/4;
System.out.println("The average is: " +avg);
return avg;
}
public static int median(int [] array) {
//i think this is way off also
int size = 0;
int[] grades = new int [size];
for(int i=0;i<size;i++){
grades[i]=0;
}
int i;
for( i=0;i<size;++i){
int count=0;
for (int j=0;j<size;++j){
if(grades[i]>grades[j]){
count++;
}
}
if(count==grades.length/4){
break;
}
System.out.print("The median is: "+grades[i]);
}
return grades[i];
}
public static int mode(int [] array) {
int maxValue = 0, maxCount = 0;
for (int i = 0; i < array.length; ++i) {
int count = 0;
for (int j = 0; j < array.length; ++j) {
if (array[j] == array[i]) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = array[i];
}
}
return maxValue;
客户端:
public class StudentGradesClient {
public static void main(String [] args){
int [] grades = new int [4];
Random rand = new Random();
for (int i = 0; i < grades.length; i++)
{
grades[i] = rand.nextInt(100) + 1;
}
StudentGrades.AscendingSort(grades);
System.out.println ("Student Grades");
for (int i = 0; i<grades.length; i++)
System.out.print(grades[i] + "\t");
System.out.println();
StudentGrades.Highest(grades);
for (int i = 1; i < grades.length; i++)
System.out.print(grades[i]);
StudentGrades.StudentAverage(grades);
for (int i = 0; i<grades.length; i++)
//some random big number keep popping up before
System.out.println();
//not printing at all
StudentGrades.median(grades);
for (int i = 0; i<grades.length; i++)
System.out.println();
}
}
结果:
Student Grades
6 23 49 65
The highest grade is: 65
234965The average is: 35
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at studentgrades.StudentGrades.median(StudentGrades.java:66)
at studentgrades.StudentGradesClient.main(StudentGradesClient.java:32)
C:\Users\Marc\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
修改
我几乎就到了!提示非常有用!现在,我在完成中位数和模式方面遇到了困难,而且在我的平均打印之前还有很多数字一直显示。
如果有人可以发布提示等 - 我不要求直接回答。我正在学习分享的帮助/提示,谢谢!在某些部分仍然有点困惑,非常感谢 - 再次感谢你!
答案 0 :(得分:2)
一些提示:
Highest
方法中,查看println
相对于计算max
的循环的位置(进一步提示:之后 >循环)grades
数组传递给StudentAverage()
和median()
StudentAverage()
中,为什么要循环100次并将计算的和除以100?新提示: