0

我正在尝试编写一个比较器,用于根据它拥有的整数对字符串列表进行排序。前任。H3232GHSD3 和 H56RFRSFR4,第一个字符串的整数为 32323,而第二个字符串的整数为 564,因此第二个字符串小于第一个字符串。

这是我的代码

import java.util.*;

// Sorts strings based on integers it contains 
class IntComparator implements Comparator<String>{

    @Override
    public int compare(String s1, String s2) {
        // Strip the non integers from strings
        s1 = s1.replaceAll("[^\\d.]","");
        s1 = s1.replaceAll("[^\\d.]","");
        // change string to integers
        int l1 = Integer.parseInt(s1);
        int l2 = Integer.parseInt(s2);

        if(l1 > l2){
            return 1;
        }
        else if(l1 < l2){
            return -1;
        }
        return 0;
    }
}
public class sample {
    public static void main(String[] args) {

        List<String> RandomString = new ArrayList<String>();

        RandomString.add("HA4ZNV0WE1");
        RandomString.add("A3XHN20WE1");
        RandomString.add("D4VH3V0WE1");

        Collections.sort(RandomString, new IntComparator());

        for(String R : RandomString){
            System.out.println(R);
        }

    }

}

这是我得到的错误

Exception in thread "main" java.lang.NumberFormatException: For input string: "HA4ZNV0WE1"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at IntComparator.compare(sample.java:13)
    at IntComparator.compare(sample.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at sample.main(sample.java:36)

谢谢,

4

4 回答 4

3

您的代码中有错字。改变 -

// Strip the non integers from strings
s1 = s1.replaceAll("[^\\d.]","");
s1 = s1.replaceAll("[^\\d.]","");

对此——

// Strip the non integers from strings
s1 = s1.replaceAll("[^\\d.]","");
s2 = s2.replaceAll("[^\\d.]",""); // In your code, you've written s1 here too.

我假设您已经复制并粘贴了第一行,但忘记更改变量名。这就是为什么有时它被称为反模式

于 2013-03-27T05:01:53.210 回答
2

注意你的代码

// Strip the non integers from strings
s1 = s1.replaceAll("[^\\d.]","");
s1 = s1.replaceAll("[^\\d.]","");

你应该把第二行变成

s2 = s2.replaceAll("[^\\d.]","");

s1在您发布的代码中,您只是两次摆脱了非数字,并且永远不会s2指向只有数字的字符串。

于 2013-03-27T05:02:14.180 回答
0

尝试[^\p{L}]代替你的正则表达式

于 2013-03-27T05:01:50.560 回答
0

尝试

        s1 = s1.replaceAll("\\D", "");
        s2 = s2.replaceAll("\\D", "");
于 2013-03-27T05:13:26.807 回答