我使用一個ArrayList舉行一個名爲boot對象建立一個目錄。字符串確實來自同一個對象不等於字符串中的一個ArrayList
我haverun到一個問題,在我的目錄類的方法之一。該方法應該遍歷目錄並找到具有匹配ID(字符串值)的引導對象。
該目錄充滿了這些對象;像這樣:
Boot boot1 = new Boot("Extreme Hiking Boot", "A123456", "For extreme terrains", "Khaki", "Canvas", "For all terrains", 65.50, 100, 5);
Boot boot2 = new Boot("Casual Hiker", "B123456", "A hiking boot for the casual person", "Brown", "Leather", "Rocky", 55.95, 200, 3);
Boot boot3 = new Boot("Broken Boot", "Y123456","A broken boot", "Yellow", "Plastic", "Soft Ground", 110.45, 400, 1);
這裏是造成問題的方法:
public double getPriceForProduct(String ID){
double price = -1.0;
for(Boot b : catalogue){
if(b.getID().equals(ID)){
price = b.getPrice();
}
else{
System.out.println("We don't have a boot with that ID in stock.");
System.out.println(b.getID()+"\n\n");
}
}
return price;
}
它這個返回到我的控制檯:
We don't have a boot with that ID in stock.
B123456
We don't have a boot with that ID in stock.
Y123456
We don't have a boot with that ID in stock.
A123456
We don't have a boot with that ID in stock.
Y123456
我有一個使用相同的先進的循環集的方法另一種方法可以很好地比較雙打。
我很困惑,爲什麼這種先進的循環無法正常工作。
「ID」的價值是什麼? – UnholySheep
你正在經歷循環,併爲循環中的每個元素做if/else ..所以,當你通過A123456時,它會爲它設置價格,但仍然打印它找不到其他兩個...你需要打印你沒有找到它後,你已經看過每個實例 – okaram
究竟是什麼問題?你必須更具體。 –