根据最后一个单词的升序对字符串进行排序

时间:2019-03-07 07:00:51

标签: java sorting comparator

我有一个存储在以下字符串的列表:

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

鉴于我的输入字符串是:

Mohammad Ali: salary is 24K, annual raise is 10% has balance of 317146.70
Steve Gates: salary is 36K, annual raise is 5% has balance of 474608.11
Michael Jordan: salary is 71K, annual raise is 7% has balance of 934461.89
Lora Star: salary is 104K, annual raise is 2% has balance of 1364777.40
Donald Kim: salary is 44K, annual raise is 1% has balance of 577470.66
Bill Jobs: salary is 54K, annual raise is 0% has balance of 706933.71

我想根据余额的升序(即字符串中的最后一个值)逐一打印字符串。

Comparator<String> cmp = new Comparator<String>() {
      public int compare(String o1, String o2) {
        return (Integer.valueOf(o1.substring(o1.lastIndexOf(" ")+1)).compareTo(Integer.valueOf(o2.substring(o2.lastIndexOf(" ")+1))));
      }
    };

    Collections.sort(unsorted, cmp);

    for (int i = 0; i < unsorted.size(); i++){
      System.out.println(unsorted.get(i));
    }
  }

但是,当我尝试运行程序时,遇到错误:

java.lang.NumberFormatException: For input string: "474608.11"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at Main$1.compare(Main.java:35)
    at Main$1.compare(Main.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.ArrayList.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at Main.main(Main.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)

我可以解决这个问题吗?

0 个答案:

没有答案