在 Java 中将数组作为 setter 传递

Pass an array as setter in Java

DITP 3113 class

package com.ditp3113;

import java.util.Scanner;//Scanner class takes input
public class Student {
    
    
    /////Decalartion of the fields
    
    private String studName;
    private String idNo;
    public static double[] marks =new double[3];//Stores marks of three tests// static to ensure this double can be used universally
    
    
    
    public Student(String studName,String idNo)
    {  ///Constructor that accepts student's name and id as arguments
        this.idNo=idNo;
        this.studName=studName;
        
        
    }
    
    
    public static void main(String []args) {
        
     model model[] =new model[3];
        
        Scanner input=new Scanner(System.in);
        
        
        Student OmarObject=new Student("Omar","B0123345");
        Student HanaObject=new Student("Hamza","B06564788");
        
        System.out.println("Please enter 3 marks for Omar:");
        
        
        for (int i=0; i<3;i++) {
        
            marks[i]=input.nextDouble();
            
           System.out.println();
                
        }
    
         
    model[0].setMarks(marks);
        
    
    System.out.println("Please enter 3 marks for Hana");
        
        
        for (int j=0; j<3;j++) {//Stores 3 marks for 3 subjects
            
            marks[j]=input.nextDouble();
            
            System.out.println();
        
            
        }
        
        model[1].setMarks(marks);
      
        double[] OmarMarks =model[0].getMarks();
        for (int i = 0; i <OmarMarks.length; i++) {
            System.out.println(OmarMarks[i]);
            
         
        } 
        
        double[] HannaMarks =model[1].getMarks();
        for (int j = 0; j <HannaMarks.length; j++) {
            System.out.println(HannaMarks[j]);
        } 
        
        
    }

}

型号class(model.java)

package com.ditp3113;

public class model {
    
    private double[] marks;
    
    

    
    public void setMarks(double[] marks) {
        
        this.marks=marks;
    }
    
    public double[] getMarks() {
        
        return marks;
    }

    
    
    
}

当我运行时,出现如下错误:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.ditp3113.model.setMarks(double[])" because "model[0]" is null
    at com.ditp3113.Student.main(Student.java:46)

你能帮我解决这个问题吗?

在执行 model = new model[3]; 时,您创建了一个大小为 3 的数组。但是,它是空的。

因此,当您执行 model[0] 时,这将 return 为空。

要解决这个问题,您应该设置值,例如model[0] = myModel;。在您的情况下,model[0] = new model(); 应该有效,但仅适用于第一项(第二项和第三项始终为空)。

有关 Java 的 NPE 的更多信息,它是 here