所以我不确定为什么下面的代码会返回“它们不相等”。从检查它应该返回“他们是平等的”。谁能帮我吗?先感谢您。
public class BenAndLiam {
public static void main(String[] args){
String[] name = new String[2];
name[0] = "Liam";
name[1] = "Short";
int[] marks = new int[3];
marks[0] = 90;
marks[1] = 50;
marks[2] = 70;
//make students
Student Liam = new Student(1111, name, marks);
Student Ben = new Student(1111, name, marks);
//print Liam's info
System.out.println(Liam.getId() + " " + Liam.getName()[0] + " " +
Liam.getName()[1] + " " + Liam.getMarks()[0] + " " + Liam.getMarks()[1] +
" " + Liam.getMarks()[2]);
System.out.println(Ben.getId() + " " + Ben.getName()[0] + " " +
Ben.getName()[1] + " " + Ben.getMarks()[0] + " " + Ben.getMarks()[1] +
" " + Ben.getMarks()[2]);
//check for equality
if(Ben.equals(Liam))
System.out.println("They're equal");
else System.out.println("They're not equal");
}
}
我的学生代码:
public class Student {
//The aspects of a student
private int id;
private String name[];
private int marks[];
//Constructor 1
public Student(int id, String name[]){
this.id = id;
this.name = name;
}
//Constructor 2
public Student(int id, String name[], int marks[]){
setId(id);
setName(name);
setMarks(marks);
}
//accessor for id
public int getId(){
return id;
}
//accessor for name
public String getName()[]{
return name;
}
//accessor for marks
public int getMarks()[]{
return marks;
}
//Mutator for id
public void setId(int id){
this.id = id;
}
//mutator for name
public void setName(String name[]){
this.name = name;
}
//Mutator for marks
public void setMarks(int marks[]){
this.marks = marks;
}
}
从表面上看,我需要为在我的学生类中使用 equals() 设置某种标题?
更新:我刚刚通过将此代码添加到我的学生类中来使其工作:
public boolean equals(Student otherstudent){
return ((id == otherstudent.id) && (name.equals(otherstudent.name)
&& (marks == otherstudent.marks)));
}
干杯伙计们!