0

For an assignment in my programming class I need to create a program that can store countries. Every country has a name, a population & an area. (KM^2)

import java.util.ArrayList;
import java.util.Arrays;

//Main Class//**

public class P820_Country_Main {
  public void run() {
    Country Nederland = new Country("Netherlands", 17000000, 41543);
    Country Duitsland = new Country("Gernany", 80620000, 357376);

    ArrayList<Country> countries = new ArrayList<Country>();
    countries.add(Nederland);
    countries.add(Duitsland);

    System.out.println(Arrays.toString(countries));
}

public static void main(String[] args) {
    new P820_Country_Main().run();
}
}

The country class:

public class Country
{
private String countryName;
private int countryPopulation;
private int countryArea;
private double populationDensity;

public Country(String countryName, Integer countryPopulation, Integer countryArea)
{
    this.countryName = countryName;
    this.countryPopulation = countryPopulation;
    this.countryArea = countryArea;
}


}

The issue I'm currently facing is that I can't seem to print out my ArrayList. Every spot of the ArrayList is basically an Array of its own. (Containing a String for the country's name, an int for the population & an int for the area. (Ignore the density variable, that is for later in the assignment)

The way I printed out ArrayList up until this point was as follows

System.out.println(countries);

When I do this with my current ArrayList it will print out the addresses instead of what's inside of the Array. How do I get it to print out the ArrayList?

1 Answers1

0

Try to declare toString() method in Country class:

public class Country
{
...

public String toString(){
    return "Name: "+countryName+", population: "+ countryPopulation + ", area: "+countryArea;
}
...
}
user6904265
  • 1,938
  • 1
  • 16
  • 21