-1

i declared the variable and initialized it but i still get this error

Code:

//Main

import java.util.Random;
import java.util.Scanner;

public class Main {


public static void main(String[] args)  
{

//  Scanner input=new Scanner(System.in);
//  Random rnd=new Random();
    StuInfo();

}
public static void StuInfo()
{
    Scanner io=new Scanner(System.in);
    Random rnd=new Random();       
    System.out.println("How many students are there?");
    student[] stu = new student[io.nextInt()];
    for (int i = 0; i < stu.length; i++)
    {
        stu[i].age = 5;

    }
}
}

//Student
 public class student {
     int age;
     double[] grade;
     String name;

}

Inputs:

4

Error:

exception in thread "main" java.lang.NullPointerException

at Main.StuInfo(Main.java:39)

at Main.main(Main.java:12)

Newb69420
  • 91
  • 1
  • 1
  • 9
  • 2
    `stu[i]` is `null`. – luk2302 Aug 15 '17 at 19:19
  • You need to work on your title game – jseashell Aug 15 '17 at 19:19
  • stu[i] is not meant to be null it is meant to be 5.... explain please? – Newb69420 Aug 15 '17 at 19:20
  • No, I am not going to explain (and not, it is not supposed to be 5), you need to start using a debugger. – luk2302 Aug 15 '17 at 19:21
  • You are access stu [5] . age ... turn to the duplicated question and scroll down to the answer from Makato (*another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.*) – GhostCat Aug 15 '17 at 19:22
  • @luk2302 No need for a debugger. Just understand that a freshly created array of objects has **null** slots. – GhostCat Aug 15 '17 at 19:22
  • @GhostCat yes, but a debugger will make OP see that the array contains n null entries. Should not have commented in the first place... – luk2302 Aug 15 '17 at 19:24
  • @luk2302 "Use a debugger" is written down quickly. For a newbie to "pick up" and get there ... could be a lot of confusing work. When he is already using an IDE ... easy. If not, and maybe just using javac on the command line ... not so easy any more. – GhostCat Aug 15 '17 at 19:25
  • It's really a moot point, either way (with or without debugger); this one should have been pretty straightforward. @Newb69420, it's not that we are trying to discourage you, but you really need to learn how to locate the source of a NullPointerException in a 40-line bare-bones program on your own should you wish to continue. – Randall Arms Aug 15 '17 at 19:40

1 Answers1

3

When you create a object array, your array fill null values. So First in your for loop you should define stu[i] = new Student(); then you can write stu[i].age = 5;

Zapateus
  • 516
  • 3
  • 8
  • 21