0

Hey guys I'm trying to get back into java. Took a class in high school a couple years ago. Right now I'm working on a small project where I want to use an array of objects but I'm having a problem with initializing the objects. Here's kinda what I have right now.

import java.util.Scanner;
public class Test{
  public static void main(String args[]){
    Scanner s=new Scanner(System.in);
    System.out.println("Welcome to Test. What is your name");
    String ans=s.nextLine();
    User[] people=new User[10];
    people[1].initializeUser(ans);
    people[1].printName();
  }
}

I'm having a run time error where I try to initializeUser. "Exception in thread "main" java.lang.NullPointerException" Here's the code for class User if it's helpful.

public class User{
   public String name;
   public User(String x){
      name=x;
   }
   public User intitializeUser(String x){
      User y=new User(x);
      return y;
   }
}

and just a quick question relating to classes.. When should I use private instead of public? Also when am I supposed to use static for methods and variables? Thanks, guys

  • You created an array of `User`s, but never populated it, so it's returning null as requested. – MeetTitan Nov 09 '15 at 01:37
  • All of the elements in your array of Users are still null. You need to initialize each of them with something like `people[1] = new User("UserName");`. Also, your `initializeUser` method in User class is spelled wrong. It has an extra 't' – Calvin P. Nov 09 '15 at 01:39
  • oh. I see what i did wrong. Thanks to everyone that answered – Lemur Licker Nov 09 '15 at 01:58

2 Answers2

0

When you create an array in Java, it's initialized with nulls. When you tried to access the User stored at index 1, the array returned the stored null, and you get an exception.

You'll need to initialize each element before you can use them.

Morgen
  • 1,010
  • 1
  • 11
  • 15
0

Regarding the below statements, people has been instantiated as an array but people[0], people[1], .., people[9] haven't been instantiated yet and therefore they are null.

User[] people=new User[10];
people[1].initializeUser(ans);
people[1].printName();

I think what you should do is to declare initializeUser as static:

public static User intitializeUser(String x) {
    User y = new User(x);
    return y;
}

Then, you can instantiate people[1] using one of the following ways:

people[1] = new User("Name"); // use constructor
people[1] = User.intitializeUser("Name"); // use static method
Bon
  • 3,073
  • 5
  • 21
  • 40