现要对华为和小米两种手机产品进行入库,本案例要求编写一个模拟商品入库的程序,可以在控制台输入入库商品的数量,最后打印出仓库中所有商品详细信息以及所有商品的总库存数和库存商品总金额。用Java的for循环
时间: 2024-10-07 15:07:26 浏览: 33
在Java中,你可以创建一个简单的模拟商品入库的程序,这里我们可以假设每个手机都有一个品牌、型号和价格属性。首先,我们需要定义一个表示手机的类,例如`Phone`,然后创建一个`Inventory`类来存储和管理这些商品。
```java
// 定义手机类 Phone
class Phone {
private String brand;
private String model;
private double price;
public Phone(String brand, String model, double price) {
this.brand = brand;
this.model = model;
this.price = price;
}
// 获取和设置属性的方法省略
@Override
public String toString() {
return "Brand: " + brand + ", Model: " + model + ", Price: " + price;
}
}
// 创建 Inventory 类用于管理商品
class Inventory {
private List<Phone> phones = new ArrayList<>();
public void addPhone(Phone phone) {
phones.add(phone);
}
public void printInventory() {
for (Phone phone : phones) {
System.out.println(phone);
}
}
public int getTotalStock() {
return phones.size();
}
public double getTotalAmount() {
double total = 0;
for (Phone phone : phones) {
total += phone.getPrice();
}
return total;
}
}
public class Main {
public static void main(String[] args) {
Inventory inventory = new Inventory();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of Huawei and Xiaomi phones to be added: ");
int numPhones = scanner.nextInt(); // 输入总数
for (int i = 0; i < numPhones; i++) {
System.out.println("Enter details for phone " + (i+1));
String brand;
String model;
double price;
if (i % 2 == 0) { // 假设每两个手机是一个品牌,交替入华米手机
brand = "华为";
} else {
brand = "小米";
}
System.out.print("Brand: ");
brand = scanner.next();
System.out.print("Model: ");
model = scanner.next();
System.out.print("Price: ");
price = scanner.nextDouble();
Phone phone = new Phone(brand, model, price);
inventory.addPhone(phone);
}
scanner.close();
inventory.printInventory();
System.out.println("\nTotal stock: " + inventory.getTotalStock());
System.out.println("Total amount: " + inventory.getTotalAmount());
}
}
```
在这个例子中,用户会被提示输入要入库的手机数量,然后按顺序输入每部手机的品牌、型号和价格。程序会按照华为和小米交替入库,并在结束后显示库存详情和总价。
阅读全文