整数に基づいて文字列リストをソートするための Comparator を作成しようとしています。元。H3232GHSD3 および H56RFRSFR4 の場合、最初の文字列の整数は 32323 ですが、2 番目の文字列の整数は 564 であるため、2 番目の文字列は最初の文字列より小さくなります。
私のコードはこちら
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)
ありがとう、