java - 创建一个用户输入数组,找到数组中行的平均值,然后在新数组中列出这些平均值?
问题描述
所以,我在需要将平均值存储到数组中的位上遇到了麻烦。我能够为每个学生等从用户那里获取输入。然后我可以正确计算成绩,但它不会给我平均数组。我有点理解为什么会这样,但如果我说实话,我不知道如何解决它。我尽可能多地阅读书籍、教授幻灯片和谷歌。
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.
解决方案
这正是你所要求的!
Arrays.toString(scoreArray)
打印数组的内容。scoreArray
有两个条目,它们被打印出来,如[43.5, 71.5]
.
换句话说:您的代码完全符合您的要求。
推荐阅读
- java - 基于表单的 weblogic 身份验证登录问题
- twitter-bootstrap - Bootstrap 4 网格 - 3 列 - 5.5 - 1 - 5.5
- ionic-framework - 离子定制键盘
- python - 在 Python 中调用相对路径
- nginx - 从 Gitlab 触发 Jenkins 作业不起作用
- python - 什么 Python 语法规则允许句点和方法调用之间有空格?
- javascript - Slack API 在不更改用户文本的情况下向用户消息添加附件
- mysql - MySQL 为 WebDAV 请求生成睡眠查询
- javascript - 如何使用jquery在控制台中将ul li值转换为数组格式
- jquery - 引导选项卡:将 NGL 查看器加载到选项卡中