用js实现一个简易的自动售货系统,售货柜中有若干种商品,每种商品有名称(name)、价格(price),库存(stock)三个属性。实现以下功能。 。售货柜可以列出当前的所有商品,每种商品显示各自的名称,库存和价格。。给售货柜补货,即给指定名称的商品添加一定数量的库存。●销售商品,给定商品的名称和数量以及顾客预支配金额,判断金额是否足够,若不够则 进行提醒,若足够则减库存并找零。提示 创建两个类,一个是售货柜类(SellingMachine),另一个是商品类(Product)。
时间: 2024-03-12 12:47:13 浏览: 53
好的,以下是用JS实现的简易自动售货系统的代码:
```javascript
class Product {
constructor(name, price, stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
}
class SellingMachine {
constructor() {
this.products = [];
}
addProduct(product) {
this.products.push(product);
}
listProducts() {
console.log("当前商品清单:");
this.products.forEach((product) => {
console.log(
`${product.name} - 库存:${product.stock} - 价格:${product.price} 元`
);
});
}
restockProduct(name, amount) {
const product = this.products.find((product) => product.name === name);
if (product) {
product.stock += amount;
console.log(`${name} 已加入 ${amount} 件库存。`);
} else {
console.log(`未找到名称为 ${name} 的商品。`);
}
}
sellProduct(name, amount, payment) {
const product = this.products.find((product) => product.name === name);
if (product) {
if (product.stock < amount) {
console.log(`${name} 库存不足。`);
} else if (product.price * amount > payment) {
console.log(`金额不足,购买 ${name} ${amount} 件需要 ${product.price * amount} 元。`);
} else {
product.stock -= amount;
const change = payment - product.price * amount;
console.log(`购买 ${name} ${amount} 件成功,找零 ${change} 元。`);
}
} else {
console.log(`未找到名称为 ${name} 的商品。`);
}
}
}
// 测试
const machine = new SellingMachine();
const coke = new Product("可口可乐", 3, 10);
const sprite = new Product("雪碧", 2.5, 5);
const chips = new Product("薯片", 5, 3);
machine.addProduct(coke);
machine.addProduct(sprite);
machine.addProduct(chips);
machine.listProducts();
machine.restockProduct("可口可乐", 5);
machine.sellProduct("雪碧", 2, 5);
```
上面的代码中,我们创建了两个类:`Product`(商品类)和`SellingMachine`(售货柜类)。`Product`类有三个属性:名称、价格和库存;`SellingMachine`类有一个属性`products`,存储了所有的商品,以及三个方法:`addProduct`(添加商品)、`listProducts`(列出所有商品)和`sellProduct`(售出商品)。其中`addProduct`和`listProducts`比较简单,`sellProduct`的实现比较复杂,需要判断商品是否存在、库存是否足够以及付款是否足够等。另外,我们还添加了一个`restockProduct`方法,用于给指定名称的商品添加库存。最后,我们进行了一些简单的测试。