我正在嘗試從 CSV 檔案中獲取 3 個 int 值并將它們加載到我可以在二次函式中使用的變數中。我遇到的問題是,當我從 CSV 中獲取值時,它們被視為字串。我試過使用,Integer.parseInt(variable); 和 Double.parseDouble(variable);。我已經嘗試使用 variable.getClass() 和列印件進行故障排除,但我不斷收到,但我不知所措
我的代碼如下:
public static void main(String[] args) {
String pathFile = "/Users/stephen/QuadData3.csv";
String line = "";
try {
BufferedReader br = new BufferedReader(new FileReader(pathFile));
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
int a = Integer.parseInt(values[0]);
int b = Integer.parseInt(values[1]);
int c = Integer.parseInt(values[2]);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我得到
Exception in thread "main" java.lang.NumberFormatException: For input string: "?4"
任何幫助將不勝感激
uj5u.com熱心網友回復:
CSV 檔案中的列/欄位很可能使用雙引號",在拆分或決議整數值之前需要將其去掉:
String[] values = line.replaceAll("\"", "").split(","); // values won't have "
或者
String[] values = line.split(",");
int a = Integer.parseInt(values[0].replaceAll("\"", ""));
// etc...
uj5u.com熱心網友回復:
最好使用 CSV 庫來讀取 CSV 檔案。SuperCSV 是一個不錯的選擇。請參考以下鏈接http://super-csv.github.io/super-csv/index.html
uj5u.com熱心網友回復:
也可以是你的“.csv”行中的一些不可列印的字符
嘗試添加此過濾器以洗掉所有這些過濾器:
int a = Integer.parseInt(values[0].replaceAll("\\P{Print}", ""));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374143.html
