0

I tried to use display method to print String array created in contstructor, but it doesn't work....

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();
}

Exception in thread "main" java.lang.NullPointerException at Student.displayDisciplines(Student.java:41) at Main.main(Main.java:5)

this is the result.

Jaehyuck Choi
  • 169
  • 11

2 Answers2

2

just edit your discipline line it will create new String Array which is not assigning class discipline field and you are printing class discipline field that's why this problem is coming.

so change

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

to

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

it will run.

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

this.student is not valid at this position you have to student field to use that.

0

It is not clear what this.students is in line. There is no such private member.

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