thread“main”java.lang.NumberFormatException:null

我是Java编程的初学者,遇到以下exception:

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; } } 

如果您尝试将字符串转换为数字,而该字符串实际上不包含数字,则会发生此exception。

例:

Integer.valueOf("10").intValue(); 可以工作,但是Integer.valueOf("abcd").intValue()抛出NumberFormatException

检查输入文件,确保你实际上有一个数字。

逐行调试器在这里非常有用。 还可以使用旧的System.out.println来查看id的值。

该exception意味着当您执行此行代码时

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

您尝试转换为整数( id )的值不是数字。

您需要仔细检查输入文件的格式。