gpt4 book ai didi

Java 将 String 转换为 Int 时产生错误

转载 作者:行者123 更新时间:2023-12-02 04:33:57 27 4
gpt4 key购买 nike

使用以下代码将 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 没有任何意义吗?另外,我该如何解决这个问题?

谢谢

最佳答案

首先,您只能解析一次并使用循环:

int programResult = Integer.parseInt(standardProgramResult);
int numbProgram=0;
for (int output: output){
numProgram += Math.abs(programResult - output)
}

也就是说,standardProgramResult 不包含整数值,无法解析。异常(exception)情况表明了这一点。

在您的代码中的某个地方可能有类似的内容:

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)
}

关于Java 将 String 转换为 Int 时产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com