2014-02-21 91 views
2

代碼:獲取java.lang.NumberFormatException代碼

我有TriangleSummer類具有類變量

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

我的主要功能是我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 

所以我得到NumberFormatException的同時行

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

讀線6號即值4。我完全無能爲力,爲什麼?

+1

_「java.lang.NumberFormatException:對於輸入字符串:」4「_您有一個額外的空間,修剪您的字符串,然後doc提及:_」字符串中的字符必須全部除了第一個字符可能是ASCII減號' - '('\ u002D')以指示負值或ASCII加號'+'('\ u002B')以指示正值以外,可能是十進制數字。 _ –

回答

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

似乎有空間的盡頭。在傳遞到Integer.parseInt(str);之前做

2

從字符串 「4」 刪除的空間,用String#trim()

It returns a copy of the string, with leading and trailing whitespace omitted 

代碼片段 -

for(String str : reader.readLine().split(" ")){ 
    triangle[j][k] = Integer.parseInt(str.trim()); 
    k++; 
}