【问题标题】:Sorting Custom Object Price Values in Ascending and Descending order按升序和降序对自定义对象价格值进行排序
【发布时间】:2013-08-16 06:30:28
【问题描述】:

我有从自定义对象获取的字符串格式的价格值,如下所示

2,000,3,000,5,000,300,-,600,-,507,-

我想按升序和降序对上述价格值进行排序

有人可以帮忙吗?

我试过这个:

 Comparator<Cars> comparator = new Comparator<Cars>() {

          @Override
          public int compare(Cars object1, Cars object2) {
          // return Float.compare(Integer.parseInt(object1.getPrice()), Integer.parseInt(object2.getPrice()));


              String price1=object1.getPrice().replaceAll(",","");
               price1=price1.replaceAll("-","");

              String price2=object2.getPrice().replaceAll(",","");
           price2=price2.replaceAll("-","");

              return ((Integer)Integer.parseInt(price1)).compareTo((Integer)Integer.parseInt(price2)); 

          }

};

但是如果我执行语句
Collections.sort(carsList, 比较器);

获取异常

例外:Error:java.lang.NumberFormatException: Invalid int: ""

【问题讨论】:

    标签: java core


    【解决方案1】:

    错误:java.lang.NumberFormatException: Invalid int: ""

    由于数组中的“-”元素而发生。当你这样做时:

               price1=price1.replaceAll("-","");
    

    新的 price1 字符串包含一个空字符串“”

    导致以下Integer.parseInt 语句以NumberFormatExcpetion 失败。

    由于parsetInt 无法将空字符串转换为数字。

    因此,一种解决方案是从数组中删除此类元素。

    或者其他解决方案是为空字符串定义一个默认值整数。比如:

               price1=price1.replaceAll("-","");
               if("".equals(price1))
                   price1="0";
    

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 2020-12-10
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2020-11-09
      • 2020-06-06
      相关资源
      最近更新 更多