提问人:INFINITY 提问时间:6/4/2021 最后编辑:INFINITY 更新时间:6/6/2021 访问量:508
如何检查用户输入是否与二维数组的元素匹配?爪哇岛
How do I check to see if a user Input matches an element of a 2D array? JAVA
问:
我正在创建一个学生成绩簿,允许用户输入他们的学生姓名和 4 个成绩,然后可以选择计算学生和班级的平均成绩,如下图所示。
使用下面的代码,我收到的学生平均值为“0.0%”并且没有错误。我是否正确地指示程序查看学生姓名是否与二维数组中的相应元素匹配?
我有程序的所有其他部分在工作。
private String[][] grades = new String[16][5];
//Declare Variables
String firstName, lastName, name;
String test1, test2, test3, test4;
test1 = t1Input.getText();
test2 = t2Input.getText();
test3 = t3Input.getText();
test4 = t4Input.getText();
firstName = firstInput.getText();
lastName = lastInput.getText();
name = firstName + " " + lastName + ": ";
grades[students][0] = name;
grades[students][1] = test1;
grades[students][2] = test2;
grades[students][3] = test3;
grades[students][4] = test4;
students++;
private void sAvgInputActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = firstInput.getText();
String lastName = lastInput.getText();
String name = firstName + " " + lastName + ": ";
int sum = 0;
double divide = 0;
for (int i = 0; i <= 1; i++) {
if (name.equals(grades[0][1])) {
for (int grade = 1; grade <= 4; grade++) {
sum = Integer.parseInt(grades[i][1]) + i;
}
break;
}
}
divide = sum / 4;
gradesOutput.setText(firstName + "'s grade average is " + divide + "%.");
}
答:
2赞
sittsering
6/4/2021
#1
将循环更改为:
//assume it as a simple table since its 2d array
//Since you are storing the name in first(0th index) column,
//only row should be loop
for (int i = 0; grades[i][0] != null; i++) {
if (name.equals(grades[i][0])) {
for (int grade = 1; grade <= 4; grade++)
//same row,different column
sum = sum + Integer.parseInt(grades[i][grade]);
break;
}
}
评论
0赞
INFINITY
6/4/2021
那奏效了!感谢您的帮助 - 我有点困惑,因为它不在我们的学校:)课程内容中
0赞
INFINITY
6/4/2021
更新@sittsering 它只找到我输入的第一个学生的平均值,其他任何学生都返回“0.0%”
0赞
sittsering
6/4/2021
有额外的支架,我把它拆掉了.
评论