Beginner in JAVA. I'm trying to print the GPA of the students. Find the below instruction the problem.
We can have only 3 grades: A, B, C correspond to the points 4,3,2. Let's say if a student has received the grades A,A,A, and B. GPA = (4+4+4+3) / 4 = 3.75.
calculateGPA should return the array of GPA of students.
Input: StudentList = {1001, 1002} studentgrades = {{'A','A','A','B'},{'A','B','B'}};
Output:(Expected)
3.75, 3.333
Output:(Actual)
4.00, 0.00
import java.util.ArrayList;
public class StudentUtil {
public static double[] calculateGPA(int[] studentIdList, char[][] studentsGrades) {
double[] Grades = new double[studentIdList.length];
for(int i = 0; i < studentsGrades.length; i++) {
double sumGrades = 0.0;
for(int j = 0; j < studentsGrades.length; j++) {
if(studentsGrades[i][j] == 'A') {
sumGrades += 4;
}
else if(studentsGrades[i][j] == 'B') {
sumGrades += 3;
}
else if(studentsGrades[i][j] == 'C') {
sumGrades += 2;
}
}
Grades[i++] = sumGrades / studentsGrades.length;
}
return Grades;
}
//(Test Case)
import static java.lang.System.out;
import java.text.DecimalFormat;
import static java.lang.System.out;
public class TestStudentUtil {
public static void main(String[] args) throws Exception {
int[] studentIdList = { 1001, 1002 };
char[][] studentsGrades = { { 'A', 'A', 'A', 'B' }, { 'A', 'B', 'B' } };
double[] results = StudentUtil.calculateGPA(studentIdList, studentsGrades);
for (double result : results) {
out.printf("%.2f\n", result);
}
}
}
The problem is in the inner loop: your loop condition is
j < studentsGrades.length, when it should bej < studentsGrades[i].lengthto iterate over all entries of the arraystudentsGrades[i].A cleaner way to write this code is to use an enhanced
forloop, since you just need the values anyway, not the indices. As well as being easier to read, this avoids the possibility of a subtle mistake like writing the wrong loop bound.The division at the end had the same problem; you need to divide by how many grades this student has, not by the number of students.
Note also that
i++is already done in your outer loop's update step, so you shouldn't also do it in the lineGrades[i] = ....