daniel p
daniel p

Reputation: 35

Unexpected getter behaviour

I'm having a little problem with the challenge assignment for one of my courses. This code is supposed to list all of the contacts contained in the array list by names of the contacts. I have made a subclass Contact which contains the number of the contact and the number.

The problem I'm having is with outputting the names of the contacts. Instead of the expected "Number of the contact" followed by the name, I only get the number. The other getter of that class works, if I change the .getName() to .getNumber() in the for loop, it will have the expected output of a "number of the contact" followed by the actual number stored in the contact.

 private void storeContact() {
    Contact contact = new Contact();
    System.out.println("Please enter a contact name.");
    contact.setName(scanner.nextLine());
    scanner.next();
    System.out.println("Please enter the phone number for the contact");
    contact.setNumber(scanner.nextLong());
    contacts.add(contact);
}
private void listAllContact(){
   if(contacts.size() != 0) {
        for (int i = 0; i < contacts.size(); i++) {
            System.out.println((i + 1) + contacts.get(i).getName());
        }
    }else{
        System.out.println("Contact book is empty.");
    }
}

Contact class:

class Contact{
    private long number;
    private String name;

    public long getNumber() {
        return number;
    }

    public void setNumber(long number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

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

Upvotes: 0

Views: 66

Answers (2)

Rafael Paulino
Rafael Paulino

Reputation: 581

The code you provided seems OK.

The problem should be when you set names and phone numbers.

If you provide them, we can search for a problem.

Upvotes: 0

Bax
Bax

Reputation: 4486

Since you did not provide a full example I tried to infer it

static List<Contact> contacts = new ArrayList<>();

public static void main(String[] args) {
    Contact contact = new Contact();
    contact.setNumber(-17);
    contact.setName("contact name");
    contacts.add(contact);
    listAllContact();
}

private static void listAllContact() {
    if (contacts.size() != 0) {
        for (int i = 0; i < contacts.size(); i++) {
            System.out.println((i + 1) + contacts.get(i).getName());
        }
    } else {
        System.out.println("Contact book is empty.");
    }
}

static class Contact {
    private long number;
    private String name;

    public long getNumber() {
        return number;
    }

    public void setNumber(long number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

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

The output is as expected

1contact name

Upvotes: 4

Related Questions