thread“main”java.lang.NumberFormatException:null

时间:2014-04-26 04:30:33

标签: java

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

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

2 个答案:

答案 0 :(得分:1)

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

示例:

Integer.valueOf("10").intValue();有效,但Integer.valueOf("abcd").intValue()会抛出NumberFormatException

检查您的输入文件,并确保您确实在那里有一个号码。

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

答案 1 :(得分:0)

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

  

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

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

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

相关问题