如何使用显示方法从构造函数中显示数组?

时间:2019-04-02 08:53:54

标签: arrays methods constructor

我试图使用显示方法来打印在contstructor中创建的String数组,但是它不起作用。...

class Person{
    public String givenName;
    public String lastName;
    public int age;
    public String gender;
    public String citizenship;
    public String[] students;

    public Person(){
        String[] students = {"Jae Choi", "Su Wu", "Harry Potter"};
        this.students = students; 
        this.givenName = "Jae";
        this.lastName = "Choi";
        this.age = 27;
        this.gender = "male";
        this.citizenship = "Korea";
    }
}


class Student extends Person{
    public double[] marks;
    public String [] diciplines;
    public int i;

    public Student(){
        double marks[] = {95.0, 50.5, 75.0};
        String diciplines[] = {"Supplementary class", "Consultation", "Extra homework"};
            for (i = 0; i < marks.length; i++){
                this.marks = marks;
                System.out.println("Student name: " + this.students[i] + " / Mark: " + this.marks[i]);
            }
    }

public void displayDisciplines(){
        String diciplines[] = {"Supplementary class", "Consultation", "Extra homework"};
        for (int i = 0; i < diciplines.length; i++){
            System.out.println("Student name: " + this.students[i] + " / Dicipline: " + this.diciplines[i]);
        }
    }

public class Main{
    public static void main(String[] args) {
        Student student = new Student();
        student.averageMarks();
        student.displayDisciplines();
}

Main.main(Main.java:5)的Student.displayDisciplines(Student.java:41)处的线程“ main”中的java.lang.NullPointerException异常

这是结果。

2 个答案:

答案 0 :(得分:2)

只需编辑您的学科行,它将创建一个新的String Array,它不会分配班级学科字段,而您正在打印班级学科字段,这就是为什么会出现此问题的原因。

所以改变

 String diciplines[] = {"Supplementary class", "Consultation", "Extra homework"};

 this.diciplines= new String[]{"Supplementary class", "Consultation", "Extra homework"}; 

它将运行。

  

System.out.println(“学生姓名:” + this.students [i] +“ /标记:”   + this.marks [i]);

此学生在此职位上无效,您必须在学生字段中使用它。

答案 1 :(得分:0)

目前尚不清楚这是什么学生。没有这样的私人成员。

System.out.println("Student name: " + this.students[i] 
  + " / Dicipline: " + this.diciplines[i]);