我创建了这个小程序..
public static void main(String[] args) {
Person P = new Person("will", "Deverson", "15/06/1987", "Bonifico");
Product PC = new Product("Asus VivoBook", "AVB2562", 799.99);
Product ROUTER = new Product("TP-Link X3", "X3-201", 142.99);
Product ADAPTER = new Product("Aukey Type-C Adapter", "C-778", 11.20);
ArrayList<Product> listProduct = new ArrayList<Product>();
listProduct.add(PC);
listProduct.add(ROUTER);
listProduct.add(ADAPTER);
//numero elementi nella lista prodotti
int nProducts = listProduct.size();
System.out.println("Il tuo carrello contiene " +nProducts +" elementi: ");
for (Product p : listProduct)
System.out.println("> name: " +p.getName() +" model: " +p.getModel() +" cost: " +p.getCost() +"€.\n");
//calcolo del totale
double total = 0;
for (Product p : listProduct){
total = total + p.getCost();;
}
当我执行时,我有以下输出:
Il tuo carrello contiene 3 elementi:
> name: C-778 model: C-778 cost: 11.2€.
> name: C-778 model: C-778 cost: 11.2€.
> name: C-778 model: C-778 cost: 11.2€.
为什么他在姓名字段中也打印了 id model ?为什么我有同一个物体 3 次?
这是您要求我发布的“Product”类:)我认为这是正确的,我唯一的疑问是在变量声明中使用“this”。
public class Product {
static String name;
static String model;
static double cost;
public Product(String n, String m, double d) {
name = m;
model = m;
cost = d;
}
public String getName(){
return name;
}
public String getModel(){
return model;
}
public double getCost(){
return cost;
}
}
看来您的“产品”类别有问题。
试试这个:
public class Product {
private String name, model;
private Double price;
public Product(String name, String model, Double price) {
this.name = name;
this.model = model;
this.price = price;
}
public String getName() {
return name;
}
public String getModel() {
return model;
}
public Double getCost() {
return price;
}
}
“Main”类看起来不错。
输出:
Il tuo carrello contiene 3 elementi:
> name: Asus VivoBook model: AVB2562 cost: 799.99€.
> name: TP-Link X3 model: X3-201 cost: 142.99€.
> name: Aukey Type-C Adapter model: C-778 cost: 11.2€.
你可以将这个:
total = total + p.getCost();
更改为:total += p.getCost();
,这与你写的相同,但更干净:-]