我有一個名為城市的陣列串列,其中包含來自另一個類的物件 City,并且該物件既包含所述城市的名稱,也包含人口。在一種方法中,我想總結所有城市人口,也就是得到這個國家的人口,但是我在 .parseLong 方法中遇到了一個例外,就像我正在做的那樣。在另一個中,我想檢查哪個城市的人口最多,但是當我列印時我什么也沒得到,也不知道如何修復它。基本上我不知道如何獲取陣列串列中物件的值。評論了我有問題以便更好地理解的地方。幫助表示贊賞!
public class Country {
private String name;
private City capital;
private int pop;
private ArrayList<City> cities;
public Country(String name, Cidade capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
cities = new ArrayList<>();
cities.add(capital);
}
public long getTotalPop(){
String c = null;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
c = iter.next();
long s = Long.parseLong(c); //giving exception here
System.out.println(s);
return s;
}
return 0;
}
public City getLargest(){
for(City city: cities){
if(city.getPop()>city.getPop()){ //method is fine but if is very wrong since am not sure what to compare to
return city;
}
}
return null;
}
}
public class City {
private String name;
private int pop;
public City(String name) {
this.name = name;
}
public City(String name, int pop) {
this.name = nome;
this.pop = pop;
}
public String getName() {
return name;
}
public int getPop() {
return pop;
}
public void setName(String name) {
this.name = name;
}
public void setPop(int pop) {
this.pop = pop;
}
}
uj5u.com熱心網友回復:
關于您的 Methode getTotalPop()
- c 應該是一個長變數并初始化為 0,因為現在您正在嘗試增加一個不可能的字串。
- 你正在迭代一個城市串列,所以 iter.next() 會給你一個城市,但你想要這個城市的人口,所以呼叫 c = iter.next().getPop();
- 您不必使用迭代器。沒關系,但在這種情況下你不會得到好處。我的建議是使用增強的 for/foreach 回圈。
所以使用這個(迭代器):
public long getTotalPop(){
long result = 0;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
result = iter.next().getPop();
}
return result;
}
或者這個(增強的 for/foreach 回圈):
public long getTotalPop(){
long result = 0;
for (City city : cities) {
result = city.getPop();
}
return result;
}
關于您的 Methode getLargest()
有一些方法可以完成這項作業,您可以使用初始化為 0 的變數最大彈出,并將每個城市人口與此變數進行比較,如果它更大,則將其設定為彈出。或者將您的第一個城市的流行設定為要比較的值。
與第一個城市:
public City getLargest() {
if (!cities.isEmpty()) {
City largest = cities.get(0);
for (int i = 1; i < cities.size(); i ) {
City city = cities.get(i);
if (largest.getPop() < city.getPop()) {
largest = city;
}
}
return largest;
}
return null;
}
此外,因為除了新的 ArrayList 之外,您沒有在建構式中初始化城市,所以不要在建構式中這樣做,而是像這樣:
private List<City> cities = new ArrayList<>();
public Country(String name, City capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
this.cities.add(capital);
}
最后,為什么這個國家的流行音樂與它擁有的所有城市的流行音樂不一樣?將 pop 初始化為 getTotalPop() 的結果是完全有意義的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/498084.html
標籤:爪哇
