我正在尝试使用compareTo方法来比较两个不同的名称。运行第一次尝试后,程序立即终止,不返回任何内容。如何修改此 compareTo 方法以比较名称(名称 n 和名称 n2)并返回结果(-1、1 或 0)?显然,可以添加打印语句以显示(相等,之前或之后)进行比较。感谢您的任何帮助。
//First attempt
public class Name implements Comparable<Name> {
private String Name;
public Name(String string) {
// TODO Auto-generated constructor stub
}
public String getName() {
return Name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
}
}
//second attempt
public class Name implements Comparable<String> {
private String Name;
public String getName() {
return Name;
}
public int compareTo(String other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
String Name = new String("jennifer");
String other = new String("paul");
}
}
//First attempt
public class Name {
public static void main(String[] args) {
String n = new String("jennifer");
String n2 = new String("paul");
if (n.compareTo(n2) < 0) {
System.out.println(n +" is before than " +n2);
} else if (n.compareTo(n2) > 0) {
System.out.println(n +" is after than " +n2);
} else if (n.compareTo(n2) == 0) {
System.out.println(n +" is equals to " +n);
}
}
}
奥托普特:
jennifer is before than paul
顺便说一下,检查一下,因为每种编程语言都有自己的一套规则和约定,而 Java 中的变量是这样的:
如果您选择的名称仅包含一个单词,请将该单词拼写为 所有小写字母。如果它由多个单词组成, 将每个后续单词的首字母大写。
public class Name implements Comparable<Name> {
private String name;
public Name(String name) {
this.name=name;
}
public String getName() {
return name;
}
public int compareTo(Name other) {
if (getName().compareTo(other.getName()) < 0) {
return -1;
} else if (getName().compareTo(other.getName()) > 0) {
return 1;
} else if (getName().equals(other.getName())) {
return 0;
}
return getName().compareTo(other.getName());
}
public static void main(String[] args) {
Name n = new Name("jennifer");
n.getName();
Name n2 = new Name("paul");
n2.getName();
System.out.println(n.getName());
System.out.println(n2.getName());
System.out.println(n2.compareTo(n));
}
}
输出: 詹妮弗保罗1