如何比较两个字符串? [重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我试图通过使用java中的比较来理解我的老师想要从这个练习中得到什么。

我不确定我需要做什么。有人能给我一个良好的开端吗?

public class BookTag implements Comparable {

    private String left;
    private int mid;
    private String right;

    public BookTag(String left, int mid, String right) {
        check(left, mid, right);
        this.left = left.toUpperCase();
        this.mid = mid;
        this.right = right.toUpperCase();
    }

    @Override
    public int compareTo(Object arg) {

        /*
         * Booktags are sorted as follows: - first go booktags with lowest left
         * attribute. If left attributes cannot discriminate... - ... first go booktags
         * with the lowest mid attribute. If mid cannot discriminate... - ... first go
         * booktags with HIGHEST right attribute.
         */

        /* COMPLETE */
        BookTag tag = (BookTag) arg; 

        return this.left.compareTo(tag.compareTo(left));


    }
}

我需要在这里比较什么价值之王?

java comparable
2个回答
1
投票

对象不能像原始类型那样自然地进行比较,因此您必须自己提供一些排序。一种方法是实现Comparable<T>接口。

public class BookTag implements Comparable<BookTag> {

     //compares this tag with another: 0 indicates equality, 1 means this is  
     //bigger, -1 means the other is bigger
     public int compareTo(BookTag other) { 

          int c = this.left.compareTo(other.left); //string implements this
          if(c != 0) { 
                return -c; //if the other's left is "smaller", this object is "bigger"
          }

          c = this.mid - other.mid;
          if(c != 0) { 
                return -c; //if the other's mid is "smaller", this object is "bigger"
          }

           c = this.right.compareTo(other.right);
           if(c != 0) { 
                return c; //if the other's right is "bigger", this object is "bigger"
          }

          return 0; //if we get here, then all values are equal, and so are the objects
     }   
}

我实现了Comparable<BookTag>而不是原始的Comparable更简单的代码。


0
投票
BookTag other = ((BookTag)o); // cast it
int leftcompare = this.left.compareTo(other.getLeft());
int midCompare = this.mid - other.getMid();
// careful with the right compare as the highest goes first
int rightCompare = this.right.compareTo(other.getRight());


// if , then, else statement to fill your teacher's requirements
// negative number means that this book tag is higher on the compare list
// 0 means cannot discriminate (move to the next field left -> mid -> right
// positive number means the other BookTag is higher on the list

而且我不知道这一个,但也许你只能权衡价值而不是if-then-else。玩得开心 :)

© www.soinside.com 2019 - 2024. All rights reserved.