簡體   English   中英

讀取CSV文件時出現NumberFormatException

[英]NumberFormatException while reading CSV file

我正在嘗試讀取CSV文件,然后將數字與ui數據進行比較。 CSV文件中有一些字段,其中沒有數字輸入,換句話說,某些字段沒有值。 我試圖將CSV文件中的所有條目轉換為Double格式:

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

但是我正在獲取NumberFormatException 如何避免呢?

檢查輸入的字符串 cost isEmpty()

if語句中替換表達式

cost!=null

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

如果您確定唯一的值是:

  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 "";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM