线程“主”java.lang.NumberFormatException:null

2024-01-02

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

如果您尝试将字符串转换为数字,但该字符串实际上并不包含数字,则会出现此异常。

例子:

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

检查您的输入文件并确保您确实有一个数字。

逐行调试器在这里会非常有用。还用旧的好System.out.println查看其中的值id.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

线程“主”java.lang.NumberFormatException:null 的相关文章

随机推荐