读取CSV文件时出现NumberFormatException

时间:2014-02-14 17:24:37

标签: java csv

我正在尝试读取CSV文件,然后将数字与ui数据进行比较。 CSV文件中有一些字段,其中没有数字条目,换句话说,某些字段没有值。我尝试将CS​​V文件中的所有条目转换为Double格式:

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

但我得到了NumberFormatException。我该如何避免呢?

2 个答案:

答案 0 :(得分:0)

检查输入 String cost isEmpty()

替换if语句

中的表达式
cost!=null

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

答案 1 :(得分:0)

如果您确定唯一的值是:

  1. 有效货币
  2. null
  3. 空字符串。
  4. 然后您可以将代码更改为

    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 "";
        }
    }
    
相关问题