这是我的两个类(class)“国家”和“国家”。我正在网上做题作为额外练习。
我需要: -向国家/地区添加一个方法 - addCountry(String name, String Capital, int Population - 通过 nextFreeCountry 填充元素并递增 nextFreeCountry
有人可以提供帮助吗?我正在努力了解如何通过 nextFreeCountry 填充元素。
国家/地区:
public class Country {
private String name;
private String capital;
private int 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];
}
添加国家/地区方法
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] =
nextFreeCountry++;
}
}
最佳答案
由于 countries
数组保存 Country
对象,因此创建一个新对象并将其放入数组中。像这样的事情:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name,capital,population);
nextFreeCountry++;
}
关于java - 用下一个空白空间填充数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28618632/