有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是初始化对象数组的正确方法吗?

public class HelloWorld{


class Student {
int marks;

}


public static void main(String []args){

Student studentArray[] = new Student[2];
studentArray[0].marks = 100;
studentArray[1].marks = 75;

int m=0;
m = studentArray[0].marks;

System.out.println(m);


    }
}

编译时没有问题,但当我执行它时,我得到空指针异常错误,如下所示:

Exception in thread "main" .lang.NullPointerException at HelloWorld.main(HelloWorld.java:13)

有人能帮我找到原因吗


共 (3) 个答案

  1. # 1 楼答案

    这就是您所要寻找的:

    public class HelloWorld{
    
    
    class Student {
        int marks;
    }
    
    
    public static void main(String []args){
    
            Student studentArray[] = new Student[2];
            studentArray[0] = new Student(); // .marks = 100;
            studentArray[1] = new Student(); // .marks = 75;
            studentArray[0].marks = 100;
            studentArray[1].marks = 75;
    
            int m=0;
            m = studentArray[0].marks;
    
            System.out.println(m);
        }
    }
    
  2. # 2 楼答案

    public class HelloWorld{
    
    public static void main(String []args){
    
            Student studentArray[] = new Student[2];
            HelloWorld helloWorld = new HelloWorld();
    
            for(int i=0; i<studentArray.length; i++) {
                studentArray[i] = helloWorld.new Student();
            }
    
            studentArray[0].marks = 100;
            studentArray[1].marks = 75;
    
            int m=0;
            m = studentArray[0].marks;
    
            System.out.println(m);
        }
    
    class Student {
        int marks;
    }
    
    }
    

    您将获得NullPointerException,因为您尚未初始化studentArray中的Student对象。然后尝试访问不存在的内容,从而出现错误

    上面的代码应该可以修复您的错误

  3. # 3 楼答案

    您创建了一个大小为2的数组,该数组指定用于保存具有Student studentArray[] = new Student[2];的学生对象,因此现在您有了一个空容器。然后,您尝试访问引发空指针异常的空容器的元素。您需要将学生对象放入学生容器中以访问容器元素