0

I have a method createCountry() and a method printAllCountries, which iterates through all countries and prints each of them if they're not null. The problem I have, is that I was only able to print out the name of one country by writing return countries[0]. However, I'd like to print all countries. Can someone therefore tell me what I need to change/consider?

...
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());
        }
    }
}
...
1
  • 2
    public Country createCountry() -> public Country[] createCountry()? Commented Sep 20, 2017 at 12:04

2 Answers 2

3

The moment you define your method, you decide what you return

So by saying public Country createCountry() you basically say I'll return a Country object.

To change that, you need to say something like public Country[] createCountry()

Sign up to request clarification or add additional context in comments.

4 Comments

Is there any other possibility? Because later I have this: Country newCountry = createCountry(); this.countries[registeredCountries] = newCountry; this.registeredCountries = this.registeredCountries + 1; break;
Well, your methods should do what their name indicates, and nothing more. If the method name is: createCountry, it should only create a country (and return it). What you want is to have another method named getAllCountries, that will return the array of countries.
That's true, but it's in another method and it's making a conflict. I have a method called run(), and this part: this.countries[registeredCountries] = newCountry; won't work when I write public Country[] in my first method..
I understand, but the right thing to do right now is to redesign your class, because currently sounds like you have a mess in there.
1

You should change the method return type to Country []. So : public Country[] createCountry()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.