首页 > 解决方案 > 创建一个用户输入数组,找到数组中行的平均值,然后在新数组中列出这些平均值?

问题描述

所以,我在需要将平均值存储到数组中的位上遇到了麻烦。我能够为每个学生等从用户那里获取输入。然后我可以正确计算成绩,但它不会给我平均数组。我有点理解为什么会这样,但如果我说实话,我不知道如何解决它。我尽可能多地阅读书籍、教授幻灯片和谷歌。

import java.util.Arrays;
import java.util.Scanner;

public class StudentGradeDriver {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        
        

                    System.out.print("Enter a number of students: ");
                    int rows = input.nextInt();

                    System.out.print("Enter a number of scores: ");
                    int columns = input.nextInt();

                    double[][] gradesArray = new double[rows][columns];

                    

                    for(int i=0 ; i<rows ; i++)
                    {
                        for(int j=0 ; j<columns ; j++)
                        {
                            System.out.printf("Please enter score %d for the student %d: ", j + 1, i +1);
                            gradesArray[i][j] = input.nextDouble();
                        }
                    }
                    
                    
                    double rowSum = 0;
                    double [] scoreArray  = new double[columns];
                    for(int i=0 ; i<rows ; i++)
                    {
                        for(int j=0  ; j<columns ; j++)
                        {
                            rowSum = rowSum + gradesArray[i][j];
                            scoreArray[j] = (double)rowSum/columns;
                            
                        }
                        System.out.printf( "The average score for student %d is: " + (double)rowSum/columns + "%n", i+1 );
                        rowSum = 0;
                        
                                             
                }
                    
                    System.out.println(Arrays.toString(scoreArray));
}
}

my output looks like, 

Enter a number of students: 5
Enter a number of scores: 2
Please enter score 1 for the student 1: 34
Please enter score 2 for the student 1: 65
Please enter score 1 for the student 2: 34
Please enter score 2 for the student 2: 76
Please enter score 1 for the student 3: 54
Please enter score 2 for the student 3: 23
Please enter score 1 for the student 4: 87
Please enter score 2 for the student 4: 65
Please enter score 1 for the student 5: 87
Please enter score 2 for the student 5: 56

The average score for student 1 is: 49.5
The average score for student 2 is: 55.0
The average score for student 3 is: 38.5
The average score for student 4 is: 76.0
The average score for student 5 is: 71.5

[43.5, 71.5] <- this should be the array, but I dont know what it is. Please go easy on me, its my first semester and I'm really struggling. Thanks for the help. 

标签: javaarrays

解决方案


正是你所要求的!

Arrays.toString(scoreArray)

打印数组的内容scoreArray两个条目,它们被打印出来,如[43.5, 71.5].

换句话说:您的代码完全符合您的要求。


推荐阅读