This question already has answers here:
Array initialization gives null pointer exception
                                
                                    (4个答案)
                                
                        
                5年前关闭。
            
        

我需要以下代码中意外输出的帮助。
我创建了一个名为“ Student”的类,而主类称为“ MainStudent”,当我尝试将Student对象设置为Array并使用setter输入数据时,我没有错误的代码,但是当我运行代码时,输​​出是像这个:


  线程“主”中的异常java.lang.NullPointerException


我正在使用NetBeans编写我的Java代码。

import javax.swing.JOptionPane;
public class MainStudent {

    public static void main(String[] args) {
        String a,b;
        int c;
        Student[] std = new Student[3];
        for(int i=0; i<std.length; i++){
            a = JOptionPane.showInputDialog("Enter Student Name");
            b = JOptionPane.showInputDialog("Enter Student Address");
            c = Integer.parseInt(JOptionPane.showInputDialog("Enter Student Phone Number"));
            std[i].setName(a);
            std[i].setAddress(b);
            std[i].setPhone_number(c);
        }

        for(int i=0; i<std.length; i++){
            System.out.println(std[i].getName());
        }
    }

}

最佳答案

您需要使用学生实例化数组。

在循环的顶部,添加:

std[i] = new Student();


该行:

Student[] std = new Student[3];


仅创建一个数据结构,能够容纳三个学生。数组中的索引实际上不包含任何内容,而实际上包含空值,这就是为什么要获取空指针的原因。您说的是“ Structure std,让我把它放在索引i中”,它会立即为您提供一个空值,因为您从未在索引i中放入任何内容。

10-06 08:58
查看更多