问题
Code :
I have TriangleSummer
class which has class variable
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
My main function is
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));
}
}
Relevant part of my computeMaxSum()
method is
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
}
and finally stack trace is
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)
for the input
2
3
1
2 1
1 2 3
4
1
1 2
4 1 2
2 3 1 1
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?
回答1:
java.lang.NumberFormatException: For input string: "4 "
It seems there is space at end. Do a trim()
before passing to Integer.parseInt(str);
回答2:
Remove the space from string "4 ", using String#trim()
It returns a copy of the string, with leading and trailing whitespace omitted
Code snippet -
for(String str : reader.readLine().split(" ")){
triangle[j][k] = Integer.parseInt(str.trim());
k++;
}
回答3:
this one will remove your spaces
int n=Integer.parseInt(br.readLine().trim());
来源:https://stackoverflow.com/questions/21940733/getting-java-lang-numberformatexception-in-the-code