gpt4 book ai didi

java - 代码中获取java.lang.NumberFormatException

转载 作者:行者123 更新时间:2023-12-01 04:55:56 25 4
gpt4 key购买 nike

代码:

我有 TriangleSummer 类,它有类变量

static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

我的主要功能是

public static void main(String args[]) throws IOException {
int noOfTestCases = Integer.parseInt(reader.readLine());
for(int i=0;i<noOfTestCases;i++){
int noOfEntries = Integer.parseInt(reader.readLine());
System.out.println(computeMaxSum(noOfEntries));
}
}

我的computeMaxSum() 方法的相关部分是

public static int computeMaxSum(int noOfEntries) throws IOException {

int[][] triangle = new int[noOfEntries][noOfEntries];

for(int j=0;j<noOfEntries;j++){
int k=0;
for(String str : reader.readLine().split(" ")){
triangle[j][k] = Integer.parseInt(str);
k++;
}
}
//further logic nothing to do with I/O
}

最后堆栈跟踪是

Exception in thread "main" java.lang.NumberFormatException: For input string: "4 "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at Matrices.TriangleSummer.main(TriangleSummer.java:17)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

输入

2
3
1
2 1
1 2 3
4
1
1 2
4 1 2
2 3 1 1

所以我在读取第 6 行时得到 NumberFormatException,即第 4 行的值

int noOfEntries = Integer.parseInt(reader.readLine());

.我完全不知道为什么?

最佳答案

 java.lang.NumberFormatException: For input string: "4 "

好像最后还有空格。在传递给 Integer.parseInt(str);

之前执行 trim()

关于java - 代码中获取java.lang.NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940733/

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