java难题,请求java大神帮助,谢谢各位?
题主可参考我的答案,亲测可用, 如果有什么不懂可追问
首先建立商品类:
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);
}
}
答案如下
上面的两个类可以放在同一包下即可
两段代码能不能放在一个包下?