首页 > 解决方案 > 关于正确实现接口的错误

问题描述

因此,该程序要求用户根据学分和学生身份计算总学费。如果是美国学生,那么每学分 700 美元和 400 美元的注册费。如果是国际学生,则每学分 1000 美元和 500 美元注册费。如果 MI 学生则每学分 500 美元和 200 美元注册费

我对程序的问题是输出应该是:

杰克的账单:6,700 美元 露西的账单:10,900 美元 郝的账单:12,500 美元

总学费收入为30,100美元

但是,我得到了这个输出(我觉得 name 和 cred hrs 的值都没有被正确获取):

空帐单:200 美元空帐单:400 美元空帐单:500 美元

总学费收入为$ 1,100

IStudent.java

public interface IStudent {

    // return the name of the student;
    String getName();

    // return the number of credit hours that this student registered
    int getCreditHours();

    // calculate the tuition for this student
    int calculateTuition();
}

IUniversity.java

public interface IUniversity {

    // return a list of students
    ArrayList<IStudent> getStudentList();

    // return a list of students
    int calculateTotalTuition();

    // add a student to student list
    void addStudent(IStudent student);
}

主.java

public class Main {

    public static void main(String[] args) {
        IUniversity mu = new University();
        IStudent  stu1 = new MichiganStudent("Jack",13);
        mu.addStudent(stu1);
        IStudent  stu2 = new USStudent("Lucy",15);
        mu.addStudent(stu2);
        IStudent  stu3 = new InternationalStudent("Hao",12);
        mu.addStudent(stu3);

        for(int i = 0; i < mu.getStudentList().size(); i++) {
            System.out.print(mu.getStudentList().get(i).getName() + 
                    "'s bill:");
            System.out.printf("\t$%,6d\n", mu.getStudentList().get(i).calculateTuition());
        }
        System.out.printf("\nThe total tuition revenue is $%,6d\n", 
                mu.calculateTotalTuitution());
    }
}

这是我的代码:

大学班:

public class University implements IUniversity {

    ArrayList<IStudent> mu = new ArrayList<IStudent>();

    public ArrayList<IStudent> getStudentList() {
        // TODO Auto-generated method stub
        return mu;
    }

    public int calculateTotalTuition() {
        // TODO Auto-generated method stub
        int tuition = 0;
        for( int i = 0; i < mu.size(); i++ ) {
            tuition = tuition + mu.get(i).calculateTuition();
        }
        return tuition;
    }

    public void addStudent(IStudent student) {
        // TODO Auto-generated method stub
        mu.add(student);
    }

}

还有一个学生班:

public class USStudent implements IStudent {

    public USStudent(String string, int i) {
        // TODO Auto-generated constructor stub
    }

    private String name;
    private int credhrs;

    public String getName() {
        // TODO Auto-generated method stub
        return name;
    }

    public int getCreditHours() {
        // TODO Auto-generated method stub
        return credhrs;
    }

    public int calculateTuition() {
        // TODO Auto-generated method stub
        int total = 0;
        total = total + 400 + (700 * credhrs);
        return total;
    }
}

标签: java

解决方案


您错过了将值存储到实例变量中。

public USStudent(String string, int i) {
    this.name = string;
    this.credhrs = i;
}

推荐阅读