2016-12-03 16 views
0

對於我的編程類中的任務,我需要創建一個可以存儲國家/地區的程序。每個國家都有一個名字,一個人口&一個地區。 (平方公里)打印一個由數組組成的ArrayList

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(); 
} 
} 

國家類:

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; 
} 


} 

我目前面臨的問題是,我似乎無法打印出我的ArrayList。 ArrayList的每個地方基本上都是它自己的一個Array。 (包含國家名稱的字符串,該區域的int爲int &(忽略密度變量,即稍後在賦值中)

我打印出ArrayList直到此時的方式是如下

System.out.println(countries); 

當我想到我當前的ArrayList它會打印出地址,而不是該數組裏面有什麼。 我如何得到它打印出的ArrayList?

+1

你應該在Country類中實現toString()方法 – user6904265

回答

0

試圖聲明在Country類中的toString()方法:

public class Country 
{ 
... 

public String toString(){ 
    return "Name: "+countryName+", population: "+ countryPopulation + ", area: "+countryArea; 
} 
... 
}