【发布时间】:2014-06-19 20:05:21
【问题描述】:
我正在尝试创建一个存储学生考试成绩的程序。
每个学生都有 4 个测试分数,必须存储在一个二维数组中。 JSwing 应用程序将允许用户输入 4 个测试标记,一旦他们单击一个按钮,它会将 4 个标记添加到数组中。
我试图通过不断收到 arrayindexboundexception 来弄清楚如何做到这一点。另外,我什至不确定我是否做得正确。
顺便说一句,这都是在JSwing完成的。
public class StudentGradesView extends FrameView {
final static int students = 15;
final static int numOfTest = 4;
//DELCARING THE 2D ARRAY
double[][] marks = new double[students][numOfTest];
public void addInfo() {
double testScores[] = new double[4];
String test1, test2, test3, test4;
double score1, score2, score3, score4;
int i = 0;
test1 = testOneIn.getText();
test2 = testTwoIn.getText();
test3 = testThreeIn.getText();
test4 = testFourIn.getText();
score1 = Double.parseDouble(test1);
score2 = Double.parseDouble(test2);
score3 = Double.parseDouble(test3);
score4 = Double.parseDouble(test4);
testScores[0] = score1;
testScores[1] = score2;
testScores[2] = score3;
testScores[3] = score4;
//First for loop starts at in the first row and automatically
//increments to the next row after the first rows columns are filled
for (int row = 0; row < marks.length; row++) {
//Second loop automatically cycles through each column in the
//current row adding test scores. After this loop finishes
//the program returns to the first loop and advances to the next
//row, at which point it will fill that row with the same test data.
for (int col = 0; col < 4; col++) {
marks[row][col] = testScores[i];
i++;
}
}
}
}
这是我目前所拥有的。任何帮助表示赞赏。
【问题讨论】:
-
为什么需要 2 个循环?
-
2 个循环,因为一个用于行,一个用于列。第一个学生有 4 个考试成绩,第二个学生有 4 个考试成绩
-
是的,OP 是对的——二维数组是合适的(行 = 学生,列 = 测试),因此使用两个循环来填充它也是如此。这里的大问题 - 我假设这是在 c/p 中将此代码放到此处的拼写错误 - 你的
marks数组在哪里创建? -
什么是“JSwing”?我不熟悉这种野兽。
-
@drewmore 这就是为什么我对为什么 2 个循环感到困惑 - 我在任何地方都看不到
marks数组。
标签: java arrays multidimensional-array indexoutofboundsexception