为什么我的compareTo()给出了错误的答案?

时间:2016-11-07 17:23:07

标签: java compareto

这是我的一些代码,它是一个for循环来创建一个有序的字符串列表a但由于某种原因它给出了其中一个数字的错误答案。

public static void main(String[] args) {
    List<String> answer = new ArrayList();
    List<String> n = new ArrayList<>();
    int w = 1327;
    int x = 17;
    int y = 15;
    int z = 12;
    n.add(Integer.toString(x));
    n.add(Integer.toString(y));
    n.add(Integer.toString(z));
    n.add(Integer.toString(w));



    while (n.size() > 0) {

        String smallest = null;
        for (String f : n) {
            if (smallest == null || smallest.compareTo(f)>0) {
                smallest = f;

            }
        }
        answer.add(smallest);
        n.remove(smallest);

预期输出为:

12
15
17
1327
1327
17
15
12

代码输出改为:

12
1327
15
17
17
15
1327
12

它打印反向的原因是因为代码的另一部分而且应该是这样的。我已经调试了它而compareTO(f)&gt; 0由于某种原因给出1327的错误int。有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

实际上,程序运行正常!! 您使用String.compareTo来比较整数...因此,15&lt; 12345但&#39; 12345&#39;&lt;&quot;&#39;&#39; 如果要对它们进行排序,则必须调整代码以使用整数。

PS:为避免编写算法,您可以使用Collections.sort();

答案 1 :(得分:0)

List<Integer> answer = new ArrayList();
    List<Integer> n = new ArrayList<>();
    int w = 1327;
    int x = 17;
    int y = 15;
    int z = 12;
    n.add(x);
    n.add(y);
    n.add(z);
    n.add(w);

    while (n.size() > 0) {

        Integer smallest = null;
        for (Integer f : n) {
            if (smallest == null || smallest>f) {
                smallest = f;

            }
        }
        answer.add(smallest);
        n.remove(smallest);
相关问题