0

I have Price Values like below in String format getting from Custom object

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

I want to Sort the above Price Values in Ascending and Descending order

Could any one help?

I have tried this:

 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)); 

          }

};

But if i execute the statement
Collections.sort(carsList, comparator);

getting the Exception

Exception:Error:java.lang.NumberFormatException: Invalid int: ""

4

1 回答 1

1

错误:java.lang.NumberFormatException:无效的 int:“”

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

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

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

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

AsparsetInt无法将空字符串转换为数字。

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

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

           price1=price1.replaceAll("-","");
           if("".equals(price1))
               price1="0";
于 2013-08-14T10:41:52.580 回答