2 回答

TA貢獻1829條經驗 獲得超4個贊
將try-catch塊放在您的迭代中
爪哇7
List<Integer> intList = new ArrayList<>();
for(String s : num) {
try {
Integer n = Integer.valueOf(s);
intList.add(n);
} catch (Exception ex) { continue; }
}
JAVA 8 流
List<Integer> intList = Arrays.asList(num)
.stream()
.map(s -> {
try {
return Integer.valueOf(s);
} catch(Exception ex) { return null;}
})
.filter(i -> i != null)
.collect(Collectors.toList());

TA貢獻2019條經驗 獲得超9個贊
如果您已經展示了迄今為止您嘗試過的內容,那將會有所幫助,但最簡單的解決方案是將您int.parse()的內容包裝在一個try/catch塊中并吞下異常。
for(int i = 0; i < items.length; i++) {
try {
newItems[i] = Itemger.parseInt(items[i]);
catch(Exception ex) {
// do nothing
}
}
添加回答
舉報