1

I have created a program and assigning customer object to customers array, but when I try to get the object in array it returns null. I am new to Java, please help me out where I am going wrong.

public class Customer {

    private String firstname,lastname;

    public Customer(String f,String l){
        this.firstname = f;
        this.lastname = l;
    }

    public String getFirstName(){
        return firstname;
    }

    public String getLastName(){
        return lastname;
    }   
}

public class Bank {

    private Customer [] customers;
    private int numberofCustomers;

    public Bank(){
        customers = new Customer [5];
        numberofCustomers = 0;

    }

    public void addCustomer(String f,String l){
        int i = numberofCustomers++;
        customers[i] = new Customer(f,l);
    }

    public int getNumberofCustomer(){
        return numberofCustomers;
    }

    public Customer getCustomerMethod(int index){
        return customers[index];
    }
}

public class TestAccount {

public static void main (String [] args){

        Bank b = new Bank();
        b.addCustomer("Test", "LastName");
        System.out.print(b.getNumberofCustomer());
        System.out.print(b.getCustomerMethod(1));

    }
}

3 Answers 3

5

Array indexes start with zero. You have added a customer at index 0 first element in your array and you should use the same index to get the element. currently there is nothing at index 1 thus your code returns null;

System.out.print(b.getCustomerMethod(0));

Say array size is 5, thus its indexs would be 0,1,2,3,4 where 0 is the first index and 4 is the last index.

After this line b.addCustomer("Test", "LastName"); your array will be :

Array: [Customer("Test", "LastName") , null , null, null, null]
Index:                0             ,  1   ,  2  ,   3 ,  4

and when you try ' System.out.print(b.getCustomerMethod(1));' It returns null. as you can see that your array has null at index 1.

Sign up to request clarification or add additional context in comments.

Comments

0

You added one customer and then you are asking for the second one. Arrays indices are zero-based.

Comments

0

There are three problems with your code:

  • Indexes start with 0
  • You are using post increment operator to assign value to i. int i = noOfCustomers++; will result in value of i as 0. So you are adding the customer at index 0 and fetching from index 1. So you get null
  • Bank should be using ArrayList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.