更新时间:2022-11-22 17:56:36
看到 NumberFormatException
时,您需要确定输入是否错误或代码错误.
When you see a NumberFormatException
, you need to decide if your input is wrong, or your code is wrong.
如果您输入的错误,则需要添加代码,例如,在***生成会产生漂亮外观错误的代码.
If your input is wrong, you need to add code that produces a nice-looking error at the top level, e.g.
try {
parseMyFile();
} catch (NumberFormatException nfe) {
System.err.println("File contains invalid numbers: "+nfe.getMessage());
}
如果要允许此输入,例如因为可以使用空字符串代替数字,检查特定输入或在循环内捕获 NumberFormatException
:
If you want to allow this input, e.g. because it's OK to have empty strings in place of numbers, check for specific input, or catch NumberFormatException
inside the loop:
for (String number : numbers){
if (number.length() != 0) {
ary[j++] = Integer.parseInt(number);
} else {
ary[j++] = 0; // In this case, zero is the same as "empty"
}
}