2014-02-14 267 views
0

我想读取一个CSV文件,然后将这些数字与ui数据进行比较。 CSV文件中有一些字段没有数字输入,换句话说,某些字段没有值。我想所有的条目转换的CSV文件格式Double阅读CSV文件时NumberFormatException

public String convertToCurrency(String cost){ 
    if(cost!=null){ 
     NumberFormat nf = NumberFormat.getCurrencyInstance(); 
     return nf.format(Double.valueOf(cost)); 
    } 
    else 
     return cost=""; 
} 

但我得到NumberFormatException。我如何避免它?

+0

首先,您使用的C#?你不能使用String.IsNullorEmpty而不是成本!= null?你得到一个有效的字符串?你知道由于语言环境,你可以得到“1,000.99”或“1.000,99”作为有效的输入吗? – jean

+0

我正在使用Java。我想我可以使用cost.isEmpty。我收到一个空字符串错误。 – maha

回答

0

检查输入是否字符串costisEmpty()

if声明

cost!=null 

替换表达

cost!=null && !cost.isEmpty() 
0

如果您确信该值只有:

  1. 有效的货币,
  2. null
  3. 空字符串。

然后,你可以更改您的代码

public String convertToCurrency(String cost){ 
    if(cost!=null && cost.length != 0){ 
     NumberFormat nf = NumberFormat.getCurrencyInstance(); 
     return nf.format(Double.valueOf(cost)); 
    } else { 
     return ""; 
    } 
} 

然而,你可能会更好做这两个包括未知(特殊)值的异常处理程序。如果你不这样做,那么你的调用函数总会有一个机会来处理你的代码中的NumberFormatException。

这里有一个额外的异常处理程序的代码:

public String convertToCurrency(String cost){ 
    if(cost!=null && cost.length != 0){ 
     try { 
      NumberFormat nf = NumberFormat.getCurrencyInstance(); 
      return nf.format(Double.valueOf(cost)); 
     } catch (NumberFormatException e) { 
      // Some appropriate logging 
      return ""; 
     } 
    } else { 
     return ""; 
    } 
}