在代码中获取java.lang.NumberFormatException [英] Getting java.lang.NumberFormatException in the code
本文介绍了在代码中获取java.lang.NumberFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
我有 TriangleSummer
类,该类具有类变量
I have TriangleSummer
class which has class variable
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行(即第4行的值4)时遇到NumberFormatException
So I am getting NumberFormatException while reading line number 6 i.e value 4 at line
int noOfEntries = Integer.parseInt(reader.readLine());
.而且我完全不知道为什么?
. And I am completely clueless so as to why?
推荐答案
java.lang.NumberFormatException: For input string: "4 "
似乎末尾有空格.在传递给 Integer.parseInt(str);
It seems there is space at end. Do a trim()
before passing to Integer.parseInt(str);
这篇关于在代码中获取java.lang.NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文