javaarraysobjectnullpointerexceptioninputmismatchexception

I am doing my homework and I stuck in one question. I am new to java. can you help me?


The question is:

Create a class person with attribute name, age and gender. Create an array of the person to hold 10 person instances. Display the information stored on the person instance in the array.

I am not sure what the question says but I tried and error comes out like this:

Exception in thread "main" java.lang.NullPointerException at instance.main(instance.java:29)

here is my code:

import java.util.Scanner;
class person{
    String name= new String();
    int age;
    String gender= new String();
    void setInfo(String Name, int Age, String Gender){
        name= Name;
        age=Age;
        gender=Gender;
    }
    void showInfo(){
        System.out.println(name+" "+ age+" "+gender);
    }
}

public class instance {
    public static void main(String[] args) { 
        Scanner sc= new Scanner(System.in);
        String name= new String();
        int age;
        String gender= new String();
        person obj[]= new person[10];
       
        System.out.println("Enter Name age and gender of 10 persons");
        for(int i=0; i<obj.length; i++)
        { 
            name=sc.nextLine();
            age=sc.nextInt();
            gender=sc.nextLine();
            obj[i].setInfo(name, age, gender);
            
        }
        for(int i=0; i<obj.length; i++){
        obj[i].showInfo();
        }
    }
}

Solution

  • You need to instantiate the class inside the array.

    for (int i = 0; i < obj.length; i++) {
        name = sc.nextLine();
        age = sc.nextInt();
        gender = sc.nextLine();
    
        //see section below
        obj[i] = new person();
        
        obj[i].setInfo(name, age, gender);
    }