Java:从方法返回数组

时间:2017-09-20 12:03:21

标签: java

我有一个方法createCountry()和一个方法printAllCountries,它遍历所有国家/地区,如果他们不是null则打印每个国家/地区。我遇到的问题是,我只能通过编写return countries[0]来打印出一个国家的名称。但是,我想要打印所有国家/地区。有人可以告诉我需要改变/考虑什么吗?

...
public Country createCountry() {

    Country[] countries = new Country[5];
    Country Sweden = new Country ("Sweden", 498000000000l,10000000);
    Country Brazil = new Country("Brazil", 1798000000000l, 208000000);
    Country Germany = new Country("Germany", 38100000000000l, 826700000);
    Country France = new Country("France", 24650000000000l, 66900000);
    Country Italy = new Country("Italy", 18500000000000l, 60600000);

    countries[0] = Sweden;
    countries[1] = Brazil;
    countries[2] = Germany;
    countries[3] = France;
    countries[4] = Italy;

    return countries; // countries[0] etc. would work..

}   

public void printAllCountries() {

    for (int i = 0; i < countries.length; i++){
        if (countries[i] != null ){
            System.out.println(countries[i].getName());
        }
    }
}
...

2 个答案:

答案 0 :(得分:3)

您定义方法的那一刻,您决定返回什么

所以说public Country createCountry()你基本上说我会返回一个Country对象。

要改变这种情况,您需要说出public Country[] createCountry()

之类的内容

答案 1 :(得分:1)

您应该将方法返回类型更改为Country []。所以: public Country[] createCountry()