我正在從 csv 文件加載一個 String 并嘗試用它創建一個 int 數組。問題是我一直遇到NumberFormatException當程序""在 String 數組中找到 a 時拋出的 a 。我不需要那些空字符串,我只需要整數。有沒有辦法避免用空字符串替換字符? aLine = aLine.replaceAll(" ", "").replaceFirst(",", ""); aLine = aLine.replace(name, "").replaceAll("\"", ""); final String[] strScores = aLine.split(","); final int[] scores = Arrays.stream(strScores) .mapToInt(Integer::parseInt).toArray();
2 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
你可以filter
流而不是空的,而不是null
在你之前parse
。喜歡,
final int[] scores = Arrays.stream(strScores) .filter(x -> x != null && !x.isEmpty()) .mapToInt(Integer::parseInt) .toArray();

繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
您應該使用數組列表,因為您可以輕松地添加和刪除
array_list<String> list = new ArrayList<String>(); // create array list
for (int i =0; i < array_string.length;i++){
if (!string_array[i].equals("")){ // filter out empty
array_list.add(string_array[i]);
}
}
String new_string_array_without_empty = array_list.toArray(new String[0]); // convert to string array again
添加回答
舉報
0/150
提交
取消