Reputation: 578
I am getting NullPointerException
in this program. I believe there's some problem in declaring Object Array.
import java.util.Scanner;
class One
{
public static void main(String args[])
{
Scanner key = new Scanner(System.in);
two[] obj = new two[3];
for (int i = 0; i < 3; i++) {
obj[i].roll = key.nextInt();
obj[i].name = key.nextLine();
obj[i].grade = key.nextLine();
}
for (int i = 0; i < 3; i++) {
System.out.println(obj[i].roll + " " + obj[i].name + " " + obj[i].grade);
}
}
}
class Two
{
int roll;
String name, grade;
}
Upvotes: 0
Views: 47
Reputation: 734
Your objects inside the array are not initialized.
Call obj[i] = new Two();
as your fist statement in the first for loop.
Btw: "two" must be uppercase "Two"
Upvotes: 0
Reputation: 393781
You forgot to initialize the objects in the array. Without this initialization, obj[i]
contains a null reference.
two[] obj=new two[3];
for(int i=0;i<3;i++)
{
obj[i] = new two();
obj[i].roll=key.nextInt();
obj[i].name=key.nextLine();
obj[i].grade=key.nextLine();
}
Upvotes: 3