我不知道该如何处理“每个循环”。
我正试图将所有人口加起来。
每次循环我都会收到错误消息。
错误显示“无法应用于给定类型”
有人可以帮我吗?
import java.util.ArrayList;
public class Canada
{
private ArrayList<ProvinceTerritory> provinces;
public Canada()
{
provinces = new ArrayList<ProvinceTerritory>();
provinces.add(null);
provinces.add(new ProvinceTerritory("Ontario",12851821));
provinces.add(new ProvinceTerritory("Quebec",7903001));
provinces.add(new ProvinceTerritory("British Columbia",4400057));
provinces.add(new ProvinceTerritory("Alberta",3645257));
provinces.add(new ProvinceTerritory("Manitoba",1208268));
provinces.add(new ProvinceTerritory("Saskatchewan",1033381));
provinces.add(new ProvinceTerritory("Nova Scotia",921727));
provinces.add(new ProvinceTerritory("New Brunswick",751171));
provinces.add(new ProvinceTerritory("Newfoundland and Labrador",514536));
provinces.add(new ProvinceTerritory("Prince Edward Island",140204));
provinces.add(new ProvinceTerritory("Northwest Territories",41462));
provinces.add(new ProvinceTerritory("Yukon",33987));
provinces.add(new ProvinceTerritory("Nunavut",31906));
}
public int getTotalPopulation()
{
int sum = 0;
for(ProvinceTerritory tempT : provinces)
{
if (tempT != null)
{
sum += tempT.getPopulation();
System.out.println(sum);
}
}
return sum;
}
}
这是“ ProvinceTerritory”类代码
public class ProvinceTerritory
{
String name;
int population;
public ProvinceTerritory(String name, int population)
{
if(name != null)
{
this.name = name;
}
else
{
throw new IllegalArgumentException ("cant be null");
}
if(population >0)
{
this.population = population;
}
else
{
throw new IllegalArgumentException ("Can not be -ve");
}
}
public String getName(String Province)
{
if (Province != null)
{
this.name = Province;
}
else
{
throw new IllegalArgumentException ("cant be null");
}
return this.name;
}
public int getPopulation(int People)
{
if (People >0)
{
this.population = People;
}
else
{
throw new IllegalArgumentException ("cant be -ve");
}
return this.population;
}
}
任何帮助将不胜感激
答案 0 :(得分:1)
问题是您没有int getPopulation()
。这就是为什么在尝试致电tempT.getPopulation()
相反,您有一个int getPopulation(int)
,它很奇怪地尝试同时充当设置者和获取者。
您可以用tempT.getPopulation(0)
来调用它,但是最好将其替换为普通的吸气剂:
public int getPopulation()
{
return this.population;
}