Reputation:
Here are my two classes Country and Countries. I am doing questions from online as extra practice.
I need to: -Add a method to Countries - addCountry(String name, String capital, int population - Which fills in the element by nextFreeCountry and increments nextFreeCountry
Can somebody provide some help? I am struggling to understand how to fill in the element by nextFreeCountry.
Country:
public class Country {
private String name;
private String capital;
private int population;
Constructor to add the name capital and population
public Country(String name, String capital, int population) {
this.name = name;
this.capital = capital;
this.population = population;
}
Get name method
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();
}
}
Countries:
class Countries {
Creating an array of Country called countries
private Country[] countries;
private int nextFreeCountry = 0;
Setting the size for the array
public Countries(int size) {
countries = new Country[size];
}
addCountry method
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] =
nextFreeCountry++;
}
}
Upvotes: 0
Views: 1800
Reputation: 317
You have to add a new country to the array which you are not doing at the moment. Like so:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name, capital, population);
nextFreeCountry++;
}
Alternatively just pass a Country to the method like this:
public void addCountry(Country country) {
countries[nextFreeCountry] = country;
nextFreeCountry++;
}
You may also be better off using an ArrayList rather than an array so you dont have to worry about the array index being out of bounds etc.
Upvotes: 1
Reputation: 68715
As countries
array hold Country
objects, so create a new object and put it in array. Something like this:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name,capital,population);
nextFreeCountry++;
}
Upvotes: 2