I am trying to access an object from an array of objects in a simple program. For hours , I have been scratching my head.
The moment I try to call the object from the array of objects using its INDEX VALUE, the output is error.
Problem: I am trying to take details from three students and store them in objects . Student s[]=new Student[2]; but when I am trying to access s[i].getName()- there is a an error.It says s[i] is null.You can see the output as shown below.
The details for three students are taken in a do-while loop until q!=1 as condition.
Here is my model class:
public class Student {
private String name;
private String id;
private int phoneNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
Here is my main
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Student s[]=new Student[2]; //I want to use an array of objects like this.
Scanner name=new Scanner(System.in);
Scanner ID=new Scanner(System.in);
Scanner phoneNumber=new Scanner(System.in);
int q=1;
do{
int i=0;
System.out.println("Enter Name");
String nameInput=name.nextLine();
s[i].setName(nameInput);
System.out.println("Enter ID");
String IDInput=ID.nextLine();
s[i].setID(IDInput);
System.out.println("Enter Phone Number");
int phoneNumberInput=phoneNumber.nextInt();
s[i].setPhoneNumber(phoneNumberInput);
i++;
} while(q!=1);
System.out.println("Name:" +s[0].getName());
System.out.println("Name:" +s[1].getName());
System.out.println("Name:" +s[2].getName());
System.out.println("ID:" +s[0].getId());
System.out.println("ID:" +s[1].getId());
System.out.println("ID:" +s[2].getId());
System.out.println("Phone:" +s[0].getPhoneNumber());
System.out.println("Phone:" +s[1].getPhoneNumber());
System.out.println("Phone:" +s[2].getPhoneNumber());
}
}
Output:
Enter Name
John
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Student.setName(String)" because "s[i]" is null
at Main.main(Main.java:28)
*Edit Note after solve: The solution demonstrates how each array element, a[i] should be instantiated within a loop. This exact concept, I did not find in the other posts.
Fixed the faulty part:
int i=0;
while(i<n){
s[i] = new Student();
System.out.println("Enter Name");
String nameInput = name.nextLine();
s[i].setName(nameInput);
System.out.println("Enter ID");
String IDInput = ID.nextLine();
s[i].setId(IDInput);
System.out.println("Enter Phone Number");
int phoneNumberInput = phoneNumber.nextInt();
s[i].setPhoneNumber(phoneNumberInput);
i++;
}