比较多个字符串和订单答案

时间:2014-08-31 11:37:06

标签: java compareto

我正在尝试比较3个不同的单词,然后对它们进行排序,但是我没有得到正确的答案。一些方向将是一个很大的帮助! Java非常新,并且长期以来一直坚持这个问题。

到目前为止,我正在使用它:

`// word1, word2, and word3 
   /* If word1 is greater than word2, 
    * and word2 IS greater than word3 and word3 is NOT greater then word1: display word1,     word2, word3 
    */
   result1  =   word1.compareTo(word2);
   result1a =   word1.compareTo(word3);
   result1b =   word2.compareTo(word3);

//display and compare information
       if (result1 > result1a + result1b)  
       JOptionPane.showMessageDialog(null, word1 + word2 + word3);

       else if (result1 < result1a + result1b)
       JOptionPane.showMessageDialog(null, word2 + word3 + word1);

`

2 个答案:

答案 0 :(得分:1)

ArrayList<String> list = new ArrayList<String>(); //create an arraylist

list.add("ccc")  //add the strings
list.add("aaa");
list.add("bbb");

Collections.sort(list); //this will sort the list in lexographical precedence

//now get the words and process as you want

答案 1 :(得分:1)

String message;
if(word2.compareTo(word1) < 0) { //word2 < word1
    if(word3.compareTo(word1) < 0) { //word3 < word1
        if(word3.compareTo(word2) < 0) { //word3 < word2
            message = word3 + word2 + word1;
        } else { //word2 <= word3
            message = word2 + word3 + word1;
        }
    } else { //word1 <= word3
        message = word2 + word1 + word3;
    }
} else { //word1 <= word2
    if(word3.compareTo(word2) < 0) { //word3 < word2
        if(word3.compareTo(word1) < 0) { //word3 < word1
            message = word3 + word1 + word2;
        } else { //word1 <= word3
            message = word1 + word3 + word2;
        }
    } else { //word2 <= word3
        message = word1 + word2 + word3;
    }
}

这是使用字典/字母顺序。如果你想用长度来比较单词,你必须用s1.compareTo(s2)替换每个s1.length() - s2.length()(如果s1大于s2,你应该有一个正整数)。