使用增强型for循环时,为什么在此程序中出现空指针异常

时间:2015-06-17 16:52:08

标签: java nullpointerexception

我在selectAllStudent方法中得到一个空指针异常。 当我使用foreach循环时,但当我使用正常循环时它工作正常。 请解释原因。谢谢

驱动程序类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) {
        Student[] sdb = new Student[2];
        try {
            for (Student s : sdb) {
                s = takeInput();
            }
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        selectAllStudent(sdb);
    }

    static void selectAllStudent(Student[] sdb) {
        for (Student s : sdb) {
            s.printStudentDetails();               // Getting NullPOinterException here
        }
    }
    public static Student takeInput() throws IOException{
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the details ");
        System.out.print("ROLL      :"); int rollno = Integer.parseInt(in.readLine());
        System.out.print("NAME      :"); String name = in.readLine();
        System.out.print("BRANCH    :"); String branch = in.readLine();
        return (new Student(rollno,name,branch));
    }  
}

学生班级

public class Student {

    private int rollno;
    private String name;
    private String branch;

    Student(int rollno, String name, String branch) {
        this.rollno = rollno;
        this.name = name;
        this.branch = branch;
    }

    void printStudentDetails() {
        System.out.println("ROLLNO  :" + rollno);
        System.out.println("NAME    :" + name);
        System.out.println("BRANCH  :" + branch);
        System.out.println("-------------------");
    }
}

1 个答案:

答案 0 :(得分:3)

您未在此Student循环中为数组分配新的for

for (Student s : sdb) {
    s = takeInput();
}

takeInput方法正确地返回Student,但您已将其分配给本地参考s,而不是作为数组sdb中的元素。数组的元素保持null,而NullPointerException来自于printStudentDetails方法中nullselectAllStudent的调用。

您可以将增强型for循环转换为标准for循环,为Student分配数组访问表达式。

for (int i = 0; i < sdb.length; i++)
{
    sdb[i] = takeInput();
}