显示等级最低和最高

时间:2016-03-09 11:08:18

标签: java arrays

如何显示最高和最低平均成绩? 我尝试了其他解决方案,但它无法正常工作

您能帮忙了解如何显示最高平均成绩和最低平均成绩

public static void main(String[] args)
{
    Scanner console = new Scanner (System.in);
    int numStud, numGrade = 0, count = 0, count2 = 0;

    double totalgrades = 0;

    System.out.println("Enter number of students:");
    numStud = console.nextInt();
    System.out.println("Enter number of student grades:");
    numGrade = console.nextInt();
    String[] students = new String [numStud];
    double [][] grades = new double [numStud][numGrade];
    double[] average = new double[numStud];
    String x = console.nextLine();

    System.out.println("");
    while(count<numStud)
    {
        System.out.println("Enter name of student " + (count + 1) + ":");
        students[count] = console.nextLine();
        System.out.println("Enter " + numGrade + " grades:");
        while(count2<numGrade)
        {
            grades[count][count2] = console.nextDouble();
            totalgrades = totalgrades + grades [count][count2];
            count2++;

        }
        average[count] = totalgrades / numGrade;
        totalgrades = 0;
        String y = console.nextLine();
        count2 = 0;
        count++;



}
count = 0;
count2 = 0;
while(count<numStud)
{
    System.out.println("The grades of " + students[count] + " are:");
    while(count2<numGrade)
    {
        System.out.println(grades[count][count2] + " ");
        count2++;
    }
    System.out.println("The average is " + average[count] + ".");
    System.out.println("");
    count2 = 0;
    count++;        
}

2 个答案:

答案 0 :(得分:0)

假设所有平均成绩保持在average数组中。然后,

Arrays.sort(average);
System.out.print("min = " + average[0] + ", max = " + average[average.length - 1]);

要填写average,您必须:

for(int j = 0; j < grades.length; ++j) {
    int sum = 0;
    for(int i = 0; i < grades[j].length; ++i) sum += grades[j][i];

    average[j] = sum / numGrade;
}

正确填写grades数组。但我建议您将while循环转换为for循环。

答案 1 :(得分:0)

要查找 最高

  • 将变量说max设置为第一个元素(或0)
  • 循环整个数组
  • 将每个数组元素的值与max
  • 进行比较
  • 如果元素值&gt; max
  • 使用元素值
  • 更新max
  • 在循环结束时,您将获得数组的最大值。

    int max = Integer.MIN_VALUE;
    for(int x=0; x<average.length; x++)
        if(average[x] > max)
            max = average[x];
    

要查找 最低

  • 将变量说min设置为第一个元素(或0)
  • 循环整个数组
  • 将每个数组元素的值与min
  • 进行比较
  • 如果元素值&lt; min
  • 使用元素值
  • 更新min
  • 在循环结束时,您将获得该数组的最小值。

    int min = Integer.MAX_VALUE;
    for(int x=0; x<average.length; x++)
        if(average[x] < min)
            min = average[x];