0

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;
}
1

2 Answers 2

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.