Hello there,

I'm working on a project and for this I'm using classes, in my main I'm using an array of objects. When I compile it, it works fine, but when I try to enter values, it displays this message:

"Exception in thread "main" java.lang.NullPointerException
at main.main(main.java:25)"

Here is my code:

public class Customer {
	
	public Customer (String theName, int theAge, int theID)
	{
		name = theName;
		age = theAge;
		ID = theID;
		
	}
	public void setName(String theName)
	{
		name = theName;
	}
	
	public void setAge(int theAge)
	{
		age = theAge;
	}
	
	public void setID(int theID)
	{
		ID = theID;
	}
	
	public String getName()
	{
		return name;
	}
	
	public int getAge()
	{
		return age;
	}
	
	public int getID()
	{
		return ID;
	}
	
	public String name;
	public int age;
	public int ID;
	
}

- customers.java

import java.util.Scanner;

public class main {

	public static void main(String args[])
	{
		int menue_choice = 0;
		int i=0;
		String inputtedName;
		Customer customers[] = new Customer[500];
		Seat seats[] = new Seat[328];
	
		Scanner in = new Scanner(System.in);
		
		System.out.println("Welcome. Please select from the following options:");
		System.out.println("\n\t\t1. Add Customer\n\t\t2. Book a seat\n\t\t3. Quit");
		menue_choice = in.nextInt();

		switch(menue_choice)
		{
			case 1: 
				    String inputted_name;
				    int inputted_age;
				   
				    customers[1].setName("Phillip");
				    System.out.println(customers[1].getName());
			break;
			
			
			case 2:
				
			break;
			
			case 3:
				
			
			break;
			
			
			case 4:
				
			break;
			
			
			default:
				
			break;
		
		}
		
		
		
	}
}

Any ideas? Thanks =)

Because your array contains all null references. When you create an array of Object (regardless of the Object type) all it creates is an array of references, but, until you assign the reference to an actual object to those slots, the slots are filled with null references.

Can you point out where the error occurs usually when you click on it, like in eclipse, it points out where the error is occurring.

I havent tried your code yet but first look I noticed line 11 in your main

Customer customers[] = new Customer[500];

try this.

Customer[] customers = new Customer[500];

this will create a customer array.

No, they both create a "Customer" array, and both create one filled with null references. Before you use one of the indexes you need to define it. i.e. in the place where you are doing customers[1].setName you first need to check whether it is defined, and, if not, define it if (customers[1] == null) customers[1] = new Customer(); And then you still need to figure out how to index into the array as I don't think you mean to always use the second element in the array, as that code currently would.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.