java难题,请求java大神帮助,谢谢各位?

编写一个商品类Product,定义属性描述商品的编号(String)、名称(String)、单价(float)、数量(int)等信息,定义4个参数的构造方法用于对商品对象的4个属性进行初始化,定义一个方法printProduct(),用于输出商品对象的四个属性值。编写一个测试类,使用泛型创建一个元素类型为Product对象的ArrayList集合,在集合对象中添加4个商品对象。遍历集合,调用每个元素的printProduct()方法,并计算输出商品的总价钱。

题主可参考我的答案,亲测可用, 如果有什么不懂可追问

    首先建立商品类:

public class Product {
/**
* 商品编号
*/
private String number;

/**
* 商品名称
*/
private String name;

/**
* 商品价格
*/
private float price;

/**
* 商品数量
*/
private int quantity;

public float getPrice() {
return price;
}

public int getQuantity() {
return quantity;
}

public Product(String number, String name, float price, int quantity) {
this.number = number;
this.name = name;
this.price = price;
this.quantity = quantity;
}

public void printProduct() {
System.out.println("商品编号:" + this.number);
System.out.println("商品名称:" + this.name);
System.out.println("商品价格:" + this.price);
System.out.println("商品数量:" + this.quantity);
}
}

2. 再建立测试类,直接运行main方法即可

public class ProductTest {
public static void main(String[] args) {
List<Product> productList = new ArrayList();
Product product1 = new Product("001", "商品1", 1f, 3);
Product product2 = new Product("002", "商品2", 1f, 1);
Product product3 = new Product("003", "商品3", 1f, 5);
Product product4 = new Product("004", "商品4", 1f, 2);
productList.add(product1);
productList.add(product2);
productList.add(product3);
productList.add(product4);
double total = 0;
for (Product product : productList) {
product.printProduct();
total += product.getPrice() * product.getQuantity();
}
System.out.println("商品总价格:" + total);
}
}



答案如下


上面的两个类可以放在同一包下即可

追问

两段代码能不能放在一个包下?

温馨提示:答案为网友推荐,仅供参考
相似回答