【问题标题】:Java: Returning an array from a method [duplicate]Java:从方法返回数组[重复]
【发布时间】:2017-09-20 12:03:21
【问题描述】:

我有一个方法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());
        }
    }
}
...

【问题讨论】:

  • public Country createCountry() -> public Country[] createCountry()?

标签: java


【解决方案1】:

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

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

要改变这种情况,你需要说类似public Country[] createCountry()

【讨论】:

  • 还有其他可能吗?因为后来我有了这个: Country newCountry = createCountry(); this.countries[registeredCountries] = newCountry; this.registeredCountries = this.registeredCountries + 1;休息;
  • 嗯,你的方法应该按照它们的名字来做,仅此而已。如果方法名是:createCountry,它应该只创建一个国家(并返回它)。你想要的是另一个名为 getAllCountries 的方法,它将返回国家/地区数组。
  • 确实如此,但它在另一种方法中并且正在产生冲突。我有一个名为 run() 的方法,这部分是:this.countries[registeredCountries] = newCountry;当我在第一种方法中编写 public Country[] 时将无法工作..
  • 我明白,但现在正确的做法是重新设计你的班级,因为目前听起来你那里一团糟。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 2018-10-15
    • 2013-02-25
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2013-05-27
    • 2011-06-30
    相关资源
    最近更新 更多