I am creating a student grade book that allows a user to input their students names and 4 grades, then have options to calculate student and class averages, as shown in the pic below.
With the code below, I am receiving the student average as "0.0%" and no errors. Am I correctly instructing the program to see if the students name matches the appropriate element in the two-dimensional array?
I have all the other parts of the program working.
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 + "%.");
}
Change the loop to this:
//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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.