包含整数的字符串的Java比较器

问题描述:

我想写一个比较器来根据它的整数对字符串列表进行排序。 ex。 H3232GHSD3和H56RFRSFR4,第一个字符串具有整数32323,而第二个字符串具有整数564,因此第二个字符串小于第一个字符串。包含整数的字符串的Java比较器

我的继承人代码

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) 

感谢,

+0

你不能将字符串转换为int。我可以在这里使用String的equals()。 – 2013-03-27 04:57:47

+0

你的正则表达式的作品我的意思是它删除所有非数字字符,请检查它。 – Abubakkar 2013-03-27 05:00:41

+0

它不执行替换 – 2013-03-27 05:01:15

尝试[^\p{L}],而不是你的正则表达式

你有一个错字你码。变化 -

// 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. 

我假设你已经复制并粘贴您的第一行,忘了改变量名。这就是为什么有时它被称为anti-pattern

+0

哦哇我不能相信我没有看到。非常感谢 – Dreadlock 2013-03-27 05:51:06

通知你的代码

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

你应该让第二行成

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

在您发布的代码,你只是摆脱在s1非数字的两倍,并从不让s2指向只有数字的字符串。

尝试

 s1 = s1.replaceAll("\\D", ""); 
     s2 = s2.replaceAll("\\D", "");