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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
vikasThakur.com
  • 578
  • 4
  • 13
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Raedwald Nov 18 '14 at 12:25

2 Answers2

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();
}
Eran
  • 387,369
  • 54
  • 702
  • 768
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"

Bene
  • 724
  • 8
  • 20