简体   繁体   中英

thread “main” java.lang.NumberFormatException: null

I'm a beginner to Java programming and I encounter the following 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

And the code:

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

This exception occurs if you try to convert a string to a number, where the string does not actually contain a number.

Example:

Integer.valueOf("10").intValue(); works, but Integer.valueOf("abcd").intValue() throws out the NumberFormatException .

Check your input file and make sure you're actually having a number there.

Line by Line debugger would be very useful here. Also use the good old System.out.println to see the value in id .

That exception means that when you are executing this line of code

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

the value you are trying to convert into an integer ( id ), isn't a number.

You need to double check your input file's format.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM