2013-10-07 71 views
0

我一直在尋找這個答案,而且我還沒有找到一個已經糾正這個問題的人。我試圖填充數組,但檢查它是否大於某個值。然而,當我運行這個,我得到一個異常在線程「主要」java.lang.NumberFormatException:對於輸入字符串:「」錯誤。下面是代碼它:String到Int的java.lang.NumberFormatException Java

public void setReadData() throws NoSuchElementException { 
    try { 

     for (int i = 0; i < getRows(); i++) { 
      String numbers = p.nextLine(); 
      String[] inputs = numbers.split(" "); 
      if (inputs.length > getCols()) { 
       System.out.println("There are more columns than the size specified!\n"); 
       System.exit(1); 
      } 
      for (int j = 0; j < getCols(); j++) { 
       int data = Integer.parseInt(inputs[j]); 
       this.setData(i,j,data); 
      } 
     } 

和錯誤代碼是:

Exception in thread "main" java.lang.NumberFormatException: For input string: "" 
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
at java.lang.Integer.parseInt(Integer.java:504) 
at java.lang.Integer.parseInt(Integer.java:527) 
at foo.Bar.setReadData(Matrix.java:49) 
at foo.Bar.main(Matrix.java:226) 

任何幫助是非常感謝!

---- ----編輯

爲了澄清,該工作的舊代碼爲:

for (int i = 0; i < getRows(); i++) { 
      p.nextLine(); 
      for (int j = 0; j < getCols(); j++) { 
       this.setData(i,j,p.nextInt()); 
      } 

     } 

然而,沒有檢查整條生產線已被檢查。

+1

顯然,'inputs [j]'是''「'。 –

+0

閱讀http://code.google.com/p/guava-libraries/wiki/StringsExplained –

+1

中有關Splitter的部分空輸入字符串不是有效的整數值。所以你可能會以空字符串結束。你確定你的數據是你相信的嗎? –

回答

0

所以我最終找到了答案。我需要在for循環上面添加一個p.nextline()以使它正確讀取下一行代碼。感謝所有人的幫助。你的回答非常感謝。

顯然,nextline所做的是抓取當前行的其餘部分,將其輸出到任何(如果有的話),然後將指針移動到下一行。這就是我遇到問題的原因。

0

試試這個:

for (int j = 0; j < getCols(); j++) { 
    if(!inputs[j].equals("")){ 
     int data = Integer.parseInt(inputs[j]); 
     this.setData(i,j,data); 
    } 
} 
+0

我很欣賞的答覆。所以我嘗試了,現在我得到這個: 線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:1 at foo.Bar.setReadData(Bar.java:49) at foo.Bar.main( Bar.java:228) – johwiltb

0
java.lang.NumberFormatException: 

當您嘗試無效的字符串轉換爲整型或此異常調用由傳遞null值parseInt()方法。

  1. 轉換無效
int var=Integer.parseInt("a");//throw NumberFormatException 
  1. 空字符串

INT VAR =的Integer.parseInt( 「」); //拋出NumberFormatException的

0

如果輸入的行包含兩個連續的空格字符,則在空格字符上拆分會導致一個空白字符,這可以解釋您的錯誤。

治療多發性空格作爲一個分隔符,這樣做:

String[] inputs = numbers.split(" +"); 

添加加號拆分正則表達式會消耗數字之間的任何多餘的空格。

相關問題