Ross
Ross

Reputation: 69

Arraylist Object not finding method

I am creating an arraylist of objects and trying to print them out. However, when I go to print it is not finding the method.

Researched arraylist Objects and copied some other code. I just can not seem to find the problem with my code.

public class Main{

   public static void main(String[] args){

  List<PhoneBook> users = new ArrayList<>();

  users.add(new PhoneBook("Paul", 4129991));
  users.add(new PhoneBook("Kelly", 5702135));

  for(int i = 0; i<users.size(); i++){
     System.out.println("PhoneBook " + PhoneBook.getName());
      }
   }
}




class PhoneBook{

  private String name; 
  private int phoneNumber;

public PhoneBook(String name, int phoneNumber){
   this.name = name;
   this.phoneNumber = phoneNumber;
}


   public String getName(){
     return name;
 }

 public int getPhoneNumber(){
   return phoneNumber;
 }

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

 public void setPhoneNumber(int phoneNumber){
    this.phoneNumber = phoneNumber;
 }



}

Upvotes: 0

Views: 702

Answers (1)

MarsAtomic
MarsAtomic

Reputation: 10696

You're running into a problem because your users data structure is an ArrayList of PhoneBook objects, which means you should be attempting to manipulate elements within the ArrayList as opposed to manipulating a PhoneBook object which does not exist.

Change your existing code from:

for(int i = 0; i<users.size(); i++){
    System.out.println("PhoneBook " + PhoneBook.getName());
}

to:

for(int i = 0; i<users.size(); i++){
    System.out.println("PhoneBook " + users.get(i).getName());
}

Your code should be iterating through each element of the ArrayList by index (your i variable) and getting the name from each item within that ArrayList. PhoneBook is the name of a class, but does not refer to the elements of your data structure. Although those elements are instances of PhoneBook, invoking the class name doesn't refer to anything in particular, which is why the compiler complains.

Upvotes: 2

Related Questions