[英]Iterator Java returns only last value
我能得到一些幫助嗎? 如何從迭代器獲取對象的所有值。 我的問題是我只得到最后一個值。 我的代碼:
class car
List<Car>car=new LinkedList<>();
.
.
public Integer getPreis(){
Iterator <Car> it = car.iterator();
Integer res = null;
while(it.hasNext()){
res=it.next();
}
return res;
}
class main
public static void main (String[]args){
Car car1 = new Car (2,"bmw",50);
Car car2 = new Car (5,"audi",20);
System.out.println(car1.getPreis);
}
我只得到 20 但我想要 50 和 20
如果你必須返回一個整數值,因此不能返回兩個整數值。
您的getPreis
例程定義不正確:如果您希望它返回所有價格(我認為這就是“preis”的意思),那么它的返回類型是錯誤的。
如果您希望它返回特定汽車的價格,那么您不需要遍歷所有汽車 - 每個汽車都已經知道自己的價格。 或者getPreis
一種getPreis
,既然你是專門在car1
上調用getPreis
方法,你為什么期望它對car2
說些什么呢?
我希望getPreis
看起來像
Integer getPreis() {
return preis;
}
你的類和構造函數看起來像
class Car {
private String model;
private int preis;
Car(int xxx, String model, int preis) {
// I don't know what the first argument is supposed to be
this.model = model;
this.preis = preis;
}
...
}
然后你可以寫
System.out.println("Price of car 1 = " + car1.getPreis());
System.out.println("Price of car 2 = " + car2.getPreis());
(如果您也編寫getModel()
代碼,則可以產生更好的輸出)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.