对象数组中的NullPointerException

时间:2016-08-08 16:30:40

标签: java nullpointerexception

这是询问用户输入的程序:5名学生的姓名和地址  通过创建对象数组并显示它们。

package StringDisplay;

import java.util.Scanner;


public class Student {


    String name;
    String address;
    Student[] studentArray = new Student[5];


    public void setInfo() {
        Scanner userName = new Scanner(System.in);
        for (int i = 0; i < 5; i++) {

            Student student = new Student();


            System.out.print("Enter Name:");
            student.name = userName.nextLine();

            System.out.print("Enter Address:");
            student.address = userName.nextLine();
            studentArray[i] = student;


        }
    }


    public void displayInfo() {
        for (int i = 0; i < 5; i++) {
            Student student = studentArray[i];
            System.out.print("NAME:" + student.name);
            System.out.print("ADDRESS:" + student.address);
        }


    }


    public static void main(String[] args) {
        Student info = new Student();
        info.setInfo();
        Student display = new Student();
        display.displayInfo();

    }
}

1 个答案:

答案 0 :(得分:0)

    Student info = new Student();
    info.setInfo();
    Student display = new Student();
    display.displayInfo();

阅读您正在制作对象的代码的简单英语&#34; info&#34;学生班级和设置信息....

然后制作学生班的新对象&#34;显示&#34;所以基本上没有任何显示对象可供您显示,因为所有信息都保存在info对象中。

希望你遇到问题......