Firstly, Im new to ArrayList. I have this program where the SalesPerson object will travel to 20 cities throughout the world. For every visit, the program will ask the user to enter name of the city, size of city, and postal code. This is done using for loop and ArrayList. But when i want to display all the cities, it print out weird character. May I know where did I went wrong?
Below is the sample output.
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
==
Enter name of city: Indonesia
Enter size of city: Big
Enter postal code: 111222
==
Cities Visited: [travellingapp.City@42a57993, travellingapp.City@75b84c92]
This is my code:
TravellingApp.java
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SalesPerson s1 = new SalesPerson();
for(int j=1; j<=20; j++)
{
System.out.print("Enter name of city: ");
String name = sc.nextLine();
System.out.print("Enter size of city: ");
String size = sc.nextLine();
System.out.print("Enter postal code: ");
int postalCode = sc.nextInt();
sc.nextLine();
System.out.println("___________________________________________");
City c1 = new City(name, size, postalCode);
s1.addCity(c1);
}
System.out.print("Cities Visited: "+ s1.returnListOfCities());
}
SalesPerson.java (Class)
public class SalesPerson {
private ArrayList<City>listOfCities = new ArrayList<City>();
public void addCity(City c1)
{
listOfCities.add(c1);
}
public ArrayList<City> returnListOfCities()
{
return listOfCities;
}
}
City.java (Class)
public class City {
private String nameOfCity;
private String sizeOfCity;
private int postalCode;
public City(String nameOfCity, String sizeOfCity, int postalCode)
{
this.nameOfCity = nameOfCity;
this.sizeOfCity = sizeOfCity;
this.postalCode = postalCode;
}
public String getNameOfCity() {
return nameOfCity;
}
public String getSizeOfCity() {
return sizeOfCity;
}
public int getPostalCode() {
return postalCode;
}
public void setNameOfCity(String nameOfCity) {
this.nameOfCity = nameOfCity;
}
public void setSizeOfCity(String sizeOfCity) {
this.sizeOfCity = sizeOfCity;
}
public void setPostalCode(int postalCode) {
this.postalCode = postalCode;
}
}