使用以下代码将String
转换为int
时,出现错误
Exception in thread "main" java.lang.NumberFormatException: For input string: "null1"
这是代码(好吧,发生错误的行):
int numbProgram=
Math.abs(Integer.parseInt(standardProgramResult) - output[0])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[1])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[2])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[3])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[4])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[5])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[6])
+ Math.abs(Integer.parseInt(standardProgramResult) - output[7]);
那么null1
意味着什么?不应该只是意味着1因为null意味着什么?而且,我该如何解决这个问题?
由于
答案 0 :(得分:3)
首先,您只能解析一次并使用循环:
int programResult = Integer.parseInt(standardProgramResult);
int numbProgram=0;
for (int output: output){
numProgram += Math.abs(programResult - output)
}
也就是说,standardProgramResult
不包含整数值且无法解析。例外是显示。
在您的代码的某处,可能具有以下内容:
standardProgramResult = someVar1 + someVar2;
而someVar1
是"null"
。
为了更好地理解和处理这种使用例外:
int programResult = 0;
try {
programResult = Integer.parseInt(standardProgramResult);
} catch (NumberFormatException e) {
System.err.println("programResult was not a number: " + programResult);
// possibly ignore error, or terminate...
// e.printStackTrace(); // prints the stack trace
// throw e; // throws the error for someone else to handle
// System.exit(1); // terminate indicating an error in execution
}
int numbProgram=0;
for (int output: output){
numProgram += Math.abs(programResult - output)
}
答案 1 :(得分:-1)
问题是standardProgramResult
是null
。您需要使用调试器来找出原因。
我有两条建议不能直接回答您的问题,但会帮助您找出问题所在:
将parseInt()
的值分配给变量,以便您可以根据需要多次重复使用结果:
int result = Integer.parseInt(standardProgramResult);
一般来说,你不应该在一行代码中做太多,因为它会使追踪错误变得更加困难。
当您拥有值数组时需要使用for循环,并且需要为数组中的每个值重复相同的任务。