我在尝试找出代码问题时遇到了问题。基本上,该程序应该是GPA计算器。
第一部分:
import java.io.*;
import java.util.ArrayList;
public class Student {
// Data
private String name;
private int student_id;
private double gpa;
private ArrayList<Integer> grades;
private int num_courses;
// Methods
// Constructor Method
public Student() {
name = "";
student_id = 0;
gpa = 0.0;
grades = new ArrayList<Integer>();
}
// Accessor Methods (getters and setters)
public void setGrade(int g) {
grades.add(g);
calcGPA();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStudent_id() {
return student_id;
}
public void setStudent_id(int student_id) {
this.student_id = student_id;
}
public double getGPA() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public int getNum_courses() {
return num_courses;
}
public void setNum_courses(int num_courses) {
this.num_courses = num_courses;
}
// Functional Methods
public void calcGPA() {
int sum_grades = 0;
for (int i=0; i<this.grades.size(); i++) {
sum_grades = sum_grades * this.grades.get(i);
}
gpa = sum_grades/this.grades.size();
}
public void displayGrades() {
for (int i=0; i<this.grades.size(); i++) {
System.out.println("Grade in course " + i + ": " + this.grades.get(i));
}
}
}
和第二节课:
import java.io.*;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student(); //Object creation/instantiation
s1.setName("John Rodgers");
s1.setStudent_id(111);
s1.setGrade(3);
s1.setGrade(4);
s1.setGrade(3);
System.out.println("Student " + s1.getName() + "\'s GPA: " + s1.getGPA());
Student s2 = new Student();
s2.setName("Jenny Marshall");
s2.setStudent_id(333);
s2.setGrade(4);
s2.setGrade(4);
s2.setGrade(3);
s2.setGrade(4);
s2.setGrade(3);
System.out.println("Student " + s2.getName() + "\'s GPA: " + s2.getGPA());
}
}
输出显示为:
Student John Rodgers's GPA: 0.0
Student Jenny Marshall's GPA: 0.0
应该计算GPA,但它显示为0.0
。
答案 0 :(得分:2)
您的calcGPA()
逻辑不正确(您正在制作0 的产品),而应该按如下所示对所有成绩求和:
public void calcGPA(){
int sum_grades = 0;
for(int i=0; i<this.grades.size(); i++){
sum_grades = sum_grades + this.grades.get(i);//sum the grades
}
gpa = sum_grades/this.grades.size();
}