0

I already defined the array of objects size. But whenever I try to set name for a customer an error happens . Here is my code :

    public static void main(String[] args) {

    int customerNum, mainChoice;

    System.out.println("Enter Total Number of Customers Using your System : ");
    Scanner input = new Scanner(System.in);
    customerNum = input.nextInt();
    Customer[] customersArray = new Customer[customerNum];
    mainMenue();
    mainChoice = input.nextInt();

    if (mainChoice == 1) {
        String askLoop = null;

        for (int i = 0; i < customerNum; i++) {
            System.out.println("Enter customer name : ");
            customersArray[i].setName(input.next());
            System.out.println("Enter customer phone number : ");
            customersArray[i].setPhoneNumber(input.next());
            System.out.println("Do you want to Add another Customer (y/n)");
            askLoop = input.next();
            if (askLoop == "y") {
                continue;
            } else {
                break;
            }

        }

    }

class Customer{
private String name;
public void setName(String name){
this.name = name;
    }
}

When I run it then I input the name the program stops and this error is displayed :

Exception in thread "main" java.lang.NullPointerException at ba_1316855_p4.BA_1316855_P4.main(BA_1316855_P4.java:30)

How can I solve this ?

Jared
  • 159
  • 2
  • 3
  • 12

4 Answers4

2

With the statement Customer[] customersArray = new Customer[customerNum]; you have only created an array of Customer class. You haven't created Customer instances yet.

you have to modify your for loop a little.

for (int i = 0; i < customerNum; i++) {
        customersArray[i] = new Customer(); // You miss this step.
        System.out.println("Enter customer name : ");
1

The line

Customer[] customersArray = new Customer[customerNum];

allocated an array of references to Customer, initialised with null's. You still need to populate the array with instances of Customer for instance in a for loop.

rsp
  • 23,135
  • 6
  • 55
  • 69
1

aren't you accessing null initialized array? your code is resulting in null.setName(something) and probably source of the NullPointerException.

0

You have declared your array filled it with any instances yet.

try

for (int i = 0; i < customerNum; i++) {
            Customer c = new Customer ();

            System.out.println("Enter customer name : ");
            c.setName(input.next());
            System.out.println("Enter customer phone number : ");
            c.setPhoneNumber(input.next());
            customersArray[i] = c;
            System.out.println("Do you want to Add another Customer (y/n)");
            askLoop = input.next();
            if (askLoop == "y") {
                continue;
            } else {
                break;
            }

        }
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64