用下一个空格填充数组?

时间:2015-02-19 22:57:10

标签: java arrays increment

这是我的两个国家和国家类。我在网上做的问题是额外练习。

我需要: - 向Country添加方法 - addCountry(String name,String capital,int population - 通过nextFreeCountry填充元素并递增nextFreeCountry

有人可以提供一些帮助吗?我正在努力了解如何通过nextFreeCountry填充元素。

国家:

public class Country {

    private String name;
    private String capital;
    private int population;

添加名称capital和population

的构造函数
    public Country(String name, String capital, int population) {
        this.name = name;
        this.capital = capital;
        this.population = population;
    }

获取名称方法

    public String getName() {
        return name;
    }


    public String getCapital() {
        return capital;
    }

    public int getPopulation() {
        return population;
    }

    public String toString() {
        return "Name = " + getName() + " Capital = " + getCapital() + " Population = " + getPopulation();
    }
}

国家:

class Countries {

创建国家/地区的数组

    private Country[] countries;
    private int nextFreeCountry = 0;

设置数组的大小

    public Countries(int size) {
        countries = new Country[size];
    }

addCountry方法

    public void addCountry(String name, String capital, int population) {
        countries[nextFreeCountry] = 
        nextFreeCountry++;
    }

}

2 个答案:

答案 0 :(得分:2)

countries数组保持Country个对象时,创建一个新对象并将其放入数组中。像这样:

public void addCountry(String name, String capital, int population) {
    countries[nextFreeCountry] = new Country(name,capital,population);
    nextFreeCountry++;
}

答案 1 :(得分:1)

您必须在阵列中添加一个新国家/地区,但目前您还没有这样做。像这样:

public void addCountry(String name, String capital, int population) {
        countries[nextFreeCountry] = new Country(name, capital, population);
        nextFreeCountry++;
}

或者只是将Country传递给这样的方法:

public void addCountry(Country country) {
            countries[nextFreeCountry] = country;
            nextFreeCountry++;
}

使用ArrayList而不是数组也可能更好,所以你不必担心数组索引超出范围等。

相关问题