我正在编写一个类方法来比较两个author对象字段。
public int compareTo(Author b) {
int i = -2;
String afn = this.firstName;
String aln = this.lastName;
String bfn = b.firstName;
String bln = b.lastName;
if(afn.equals(bfn)) { i++; }
if(aln.equals(bln)) { i++; }
return i;
} 但是,当我通过具有不同字符串的author对象时,它仍然返回零。我的方法有什么问题吗?这个方法也是必要的吗?
这是课程。
public class Author {
String firstName = TITLE_NOT_SET;
String lastName = TITLE_NOT_SET;
int birth = YEAR_NOT_SET;
int death = YEAR_NOT_SET;
public Author(String ln, String fn) {
String lastName = ln;
String firstName = fn;
}
public int getDeath() {
return death;
}
public int getBirth() {
return birth;
}
public void setDates(int b) {
if(b > 2018 || b < -2000) { b = birth; }
birth = b;
}
public void setDates(int b, int d) {
if(b > 2018 || b < -2000) { b = birth; }
if(d < b) { d = death; }
birth = b;
death = d;
}
public int compareTo(Author b) {
int i = -2;
String afn = this.firstName;
String aln = this.lastName;
String bfn = b.firstName;
String bln = b.lastName;
if(afn.equals(bfn)) { i++; }
if(aln.equals(bln)) { i++; }
return i;
}
public String toString() {
return lastName + ", " + firstName;
}
}发布于 2013-11-06 01:21:32
代码中有一些错误。导致您的问题的直接原因是您的构造函数正在隐藏实例变量,因此它们在构造时不会像您在测试类的toString方法时看到的那样发生变化。
public Author(String ln, String fn) {
String lastName = ln; //Remove 'String'
String firstName = fn; //Remove 'String'
}按照我的风格,我会把构造函数写成这样:
public Author(String lastName, String firstName) {
this.firstName = firstName; //Using the 'this' makes it clear to me exactly what I wish to happen...
this.lastName = lastName;
}‘'Shadowing是一个更高作用域的变量被阻塞的地方,因为它与一个更近的作用域中的变量共享它的名称(在实践中通常是一个参数,但它可以是一个声明在那里的变量)。因为它们都有相同的名称--使用最接近作用域的名称--以减少歧义,所以可以使用this关键字访问实例作用域,或者使用ClassName访问静态变量。主要要记住的是,在声明变量时,编译器不一定会告诉您您隐藏了一个变量,因为它可能是有意的,因此如果您重用名称,请确保在您希望的范围内访问该变量。也许更多的帮助这里..。
https://stackoverflow.com/questions/19802152
复制相似问题