這裏是使用ArrayList對計算機零件商店的目錄建模的類的代碼。所有包含的對象(產品)都已定義,包括獲取和設置數量變量的方法。找不到在對象的類中定義的符號(方法)
import java.util.*;
public class AvailablesCatalog {
public AvailablesCatalog(List cat1) {
Motherboard item1 = new Motherboard("MD4652", 1995, "Lenovo", 100.50, "Intel", 32, 5, 0);
CPU item2 = new CPU("RTJ357", 1850, "Intel", 182.50, 2.9, 6, 0);
Graphics item3 = new Graphics("P99E0", 2014, "AMD", 70.50, "AMD", 6, 0);
RAM item4 = new RAM("THN46", 1999, "Microsoft", 30.50, "DDR2", 4, 1600, 0);
HD item5 = new HD("M9052", 2001, "LG", 100, "SSD", 2.5, 750, 0);
Monitor item6 = new Monitor("D42", 2006, "LG", 200, "LED", 17.5, "1920x1080", "HDMI", 0);
Keyboard item7 = new Keyboard("F16", 2010, "Microsoft", 25.70, "Wireless", 0);
Mouse item8 = new Mouse("JERRY", 2010, "Microsoft", 30.50, "Laser", "Wireless", 0);
Printer item9 = new Printer("PRNTR", 1995, "Lexmark", 40.50, "Laser", "Colored", 0);
cat1.add(item1);
cat1.add(item2);
cat1.add(item3);
cat1.add(item4);
cat1.add(item5);
cat1.add(item6);
cat1.add(item7);
cat1.add(item8);
cat1.add(item9);
}
public String toString(List cat1) {
int flag = 0;
for(int i=0; i<cat1.size(); i++) {
if(cat1.get(i).getQuantity() != 0) {
System.out.println(cat1.get(i).toString());
}
else {
flag ++;
}
}
if(flag == 9) {
System.out.println("No products");
}
return "-------------------------------------------------------------------------";
}
}
正如你所看到的,我試圖在AvailablesCatalog類中使用getQuantity()方法。問題是,當我嘗試編譯時,getQuantity方法找不到符號錯誤。這是否意味着我實際上需要在目錄類中定義方法?在這種情況下,我如何讓它返回每個不同產品的數量?提前致謝。
編輯:因爲我沒有說清楚,所有的產品對象都有一個共同的產品超類。然後,我應該改變 的toString(表CAT1)
到
toString(List<Product> cat1)
?
編輯2:事實的確如此,唯一的問題是我在所有的產品中定義了getQuantity(),而不是基類(Product)再次感謝所有人。
你會想太多更新在構造函數中的參數。 –