Rashid Faheem Rashid Faheem -4 years ago 109
Java Question

Print ArrayList(My Datatype) using For Each Loop Not Working

Here is my code of UserDetail class.

public class UserDetail {

public void user_detail() {

Members m1=new Members("Rashid Faheem","0312-6193172","House No. 430, Street No. 5 Mehmood Abad Pindora, Rawalpindi");
Members m2=new Members("Yawar Hayat","0312-6193172", "RajanPur");
Members m3=new Members("Azhar Malik", "0312-6193172", "RajanPur");
Members m4=new Members("Muhammad Ali", "0312-6193172", "RajanPur");
Members m5=new Members("Muhammad Nazik", "0312-6193172", "RajanPur");

ArrayList<Members> al = new ArrayList<Members>();

al.add(m1);
al.add(m2);
al.add(m3);
al.add(m4);
al.add(m5);

System.out.println("These are our Members.");

For (Members m:al) {

System.out.println(m.getName());
}


}


}


Here is code from Members Class which I am using as DataType in ArrayList.

public class Members {

private String name, phone,address;


public Members(String name, String phone, String address) {
name=name;
phone=phone;
address=address;

}

public String getName() {
return name;
}

public String getPhone() {
return phone;
}

public String getAddress() {
return address;
}
}


It's giving me an error in for Each loop at three points when I triy to print all ArrayList elements on screen. First


Members cannot be resolved to a variable


Secondly


m cannot be resolved to a variable


Thirdly


Syntax error, insert ";" to complete Statement


When I try to use this statement to print ArrayList elements.

System.out.println(al);


It give me this output.


"These are our Members." [Members@1f96302, Members@14eac69,
Members@a57993, Members@1b84c92, Members@1c7c054]


How to properly print ArrayList elements using for each loop?

Update
Thanx you guys. I changed my code according to your advice but another problem now. I am only getting name but not phone and address.

Answer Source
for (Members m:al) {

    System.out.println(m.getName());
}

Notice the lowercase f. Just a typo.

EDIT:

Your constructor is also just assigning the constructor arguments to themselves. You need to assign the constructor arguments to the class variables.

public Members(String name, String phone, String address) {
    this.name = name;
    this.phone = phone;
    this.address = address;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download