如何比较两个字符串并使用compareTo方法返回字典顺序结果?

时间:2016-02-19 07:09:07

标签: java string compare getter comparable

我正在尝试使用compareTo方法来比较两个不同的名称。运行第一次尝试后,程序立即终止而不返回任何内容。如何修改此compareTo方法以比较名称(名称n和名称n2)并返回结果(-1,1或0)?显然,可以添加一个print语句来显示(等于,之前或之后)以进行比较。感谢您的帮助。

//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");
        }
    }

2 个答案:

答案 0 :(得分:1)

//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);
        }
    }   
}

Outoput:

jennifer is before than paul

顺便说一句,check this out因为每种编程语言都有自己的一套规则和约定,而Java中的变量是这样的:

  

如果您选择的名称只包含一个单词,请拼写该单词   所有小写​​字母。如果它由多个单词组成,   将每个后续单词的第一个字母大写。

答案 1 :(得分:-1)

AppDelegate

输出:  詹妮弗 保罗 1