-2

I am writing a program in which I have to create a method that finds a CustomerAccount object by the registration number associated with it. I also need to use a custom exception for when the registration number can't be found in the ArrayList of CustomerAccount objects.

My method throws the exception when trying to search for an invalid registration number, but does not print anything when searching for a valid registration number.
I want the method to output all the attributes associated with the correct customer account.

Here's the method I have so far:

public CustomerAccount findCustomer(String regNum){

    CustomerAccount correctAccount = new CustomerAccount("","",null,0);

    for (int i = 0; i < this.customerAccounts.size(); i++) {

        if (regNum.equals(customerAccounts.get(i).getTypeOfVehicle()
                .getRegNum())) {
            correctAccount = customerAccounts.get(i);
            return correctAccount;

        } else {

            try {

                throw new CustomerNotFoundException("Customer Not Found");

            } catch (CustomerNotFoundException e) {
                    e.printStackTrace();
            }
        }

    }

    return correctAccount;

}

I'm a new programmer so I apologise if the answer is obvious but after quite a while scrolling through forums I still can't figure it out!

Amanda
  • 1
  • Implement `toString` method on `CustomerAccount` and print it. Also, the title does not denote the problem – Thiyagu Mar 29 '18 at 18:23
  • What type of object is `customerAccounts`? Also, you should re-examine the way in which you're using the try/catch clauses. – chb Mar 29 '18 at 18:36

1 Answers1

0

You need to implement "toString()" in your CustomerAccount

Something like this:

public class CustomerAccount {
    private String id;
    private String name;
    private String email;

    public CustomerAccount(String id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    @Override
    public String toString() {
        return "CustomerAccount{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

And then you can use it like:

CustomerAccount customerAccount = new CustomerAccount("1","TestUser", "TestMail");
System.out.println(customerAccount.toString());
Sergey
  • 54
  • 1
  • 6
  • I tried this but the method still returns nothing when searching for a valid registration number – Amanda Apr 02 '18 at 16:12