2014-04-26 50 views
-5

我是一個初學者到Java編程,我會遇到以下異常:線程 「主要」 java.lang.NumberFormatException:空

Exception in thread "main" java.lang.NumberFormatException: null 
      at java.lang.Integer.parseInt(Integer.java:454) 
      at java.lang.Integer.valueOf(Integer.java:582) 
      at ReadWrite.ReaderStudent.Read(ReaderStudent.java:35) 
      at ReadWrite.Writer.main(Writer.java:24) 
     Java Result: 1 

,代碼:

package ReadWrite; 

import java.io.DataInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
import Student.*; 

public class ReaderStudent { 
    public Student[] Read() { 
     Student[] S; 
     S = new Student[10]; 
     try { 
      FileInputStream is = new FileInputStream(new File("d:\\JavaProjects\\JavaLab_04_B\\data.txt")); 
      String str, gr; 
      String id; 
      int id1; 
      DataInputStream ids = new DataInputStream(is); 
      for (int i = 0; i < 10; i++) { 
       str = ids.readLine(); 
       gr = ids.readLine(); 
       id = ids.readLine(); 
       id1 = Integer.valueOf(id).intValue(); 
       S[i] = new Student(str, gr, id1); 
      } 
     } catch (IOException e) { 
      System.out.println("Error writing file" + e); 
     } 
     return S; 
    } 
} 
+0

您的代碼非常難以閱讀。如果你是初學者,你應該做的第一件事是學習正確的代碼格式化做法。我建議你[從這裏開始](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.1-braces)。 – Daniel

+0

爲什麼不使用'Integer.parseInt()'方法將字符串轉換爲整數。 –

+0

valueOf:返回保存指定String值的Integer對象。該參數被解釋爲表示一個帶符號的十進制整數,就好像參數被賦予parseInt(java.lang.String)方法一樣。「所以,相同的區別。 – azurefrog

回答

0

這個例外手段當你正在執行這行代碼

id1 = Integer.valueOf(id).intValue();

您嘗試轉換爲整數的值(id)不是數字。

您需要仔細檢查輸入文件的格式。

1

如果您嘗試將字符串轉換爲數字,而字符串實際上不包含數字,則會發生此異常。

例子:

Integer.valueOf("10").intValue();作品,但Integer.valueOf("abcd").intValue()拋出的NumberFormatException

檢查您的輸入文件,並確保您確實在那裏有一個數字。

逐行調試器在這裏非常有用。還可以使用舊版System.out.println查看id中的值。

相關問題