因此,此程序要求用户根据所需的学时和学生状态来计算总学费。如果是美国学生,则每信用小时$ 700,并支付$ 400的注册费。如果是国际学生,则每学时1000美元,并收取500美元的注册费。如果是MI学生,则每学时$ 500,并收取$ 200的注册费
该程序的问题是输出应为:
杰克的账单:$ 6,700 露西的账单:$ 10,900 郝的帐单:$ 12,500总学费收入为$ 30,100
但是,我得到了这个输出(我感觉name和cred hrs的值都没有正确获取):
零食:$ 200 空的账单:$ 400 空的帐单:$ 500总学费收入为1100美元
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);
}
Main.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;
}
}
答案 0 :(得分:1)
您错过了将值存储到实例变量中的操作。
public USStudent(String string, int i) {
this.name = string;
this.credhrs = i;
}
答案 1 :(得分:0)
如果没有为实例变量提供显式初始化,则将根据变量的数据类型将其初始化为默认初始值。这是默认的JVM行为。
在您的代码段中,JVM做了以下操作:
private String name = null;
private int credhrs=0;
当您使用参数化构造函数时,您的意图是使用与对象一起传递的值。因此,在构造函数中对私有变量进行重整化将解决此问题。
user7提及的示例与上述相同。