设计一个Java语言的仓库管理系统
时间: 2024-05-04 11:19:16 浏览: 22
好的,这里是一个简单的仓库管理系统的Java代码示例:
```
import java.util.*;
class Product {
String name;
int quantity;
public Product(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
}
public class Warehouse {
Map<String, Product> inventory;
public Warehouse() {
inventory = new HashMap<>();
}
public void addProduct(String name, int quantity) {
if (inventory.containsKey(name)) {
Product product = inventory.get(name);
product.quantity += quantity;
} else {
Product product = new Product(name, quantity);
inventory.put(name, product);
}
}
public void removeProduct(String name, int quantity) {
if (inventory.containsKey(name)) {
Product product = inventory.get(name);
if (product.quantity >= quantity) {
product.quantity -= quantity;
} else {
System.out.println("Error: Not enough " + name + " in stock.");
}
} else {
System.out.println("Error: " + name + " not found in inventory.");
}
}
public void printInventory() {
System.out.println("Current Inventory:");
for (String name : inventory.keySet()) {
Product product = inventory.get(name);
System.out.println(name + ": " + product.quantity);
}
}
public static void main(String[] args) {
Warehouse warehouse = new Warehouse();
warehouse.addProduct("Apples", 10);
warehouse.addProduct("Oranges", 5);
warehouse.printInventory();
warehouse.removeProduct("Apples", 5);
warehouse.printInventory();
warehouse.removeProduct("Bananas", 3);
warehouse.printInventory();
}
}
```
这个示例代码实现了一个简单的仓库管理系统,其中`Product`类代表产品,包含产品名称和数量。`Warehouse`类代表仓库,包含了一个`inventory`哈希表来存储产品和其数量。主要的方法包括`addProduct()`来添加产品到仓库,`removeProduct()`来从仓库中移除产品,和`printInventory()`来打印当前库存清单。在`main()`方法中,我们创建了一个新的仓库对象,添加了一些产品,并且打印了当前的库存清单。然后我们移除了一些产品,再次打印了库存清单来确认移除操作的正确性。