Java 编写一个智能购物计算小程序,在一家商店有书本、铅笔、橡皮、可乐、零食五种商品,商品价格如下表所示。假如小明带了20元,且必须购买一本书,剩余的钱还可以购买哪种商品,可以购买几件,购买完后又能剩余多少钱?
时间: 2024-10-15 20:22:25 浏览: 67
当然,我们可以编写一个简单的Java程序来解决这个问题。首先,我们需要创建一个商品类(Product),包含商品名称、价格和数量属性,然后定义一个主函数(main function)来进行计算。
```java
class Product {
String name;
double price;
// 构造函数
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// 获取商品信息的方法
@Override
public String toString() {
return "商品:" + name + ", 价格:" + price;
}
}
public class ShoppingCalculator {
static final Product book = new Product("书", 10);
static final Product pencil = new Product("铅笔", 2);
static final Product eraser = new Product("橡皮", 1);
static final Product coke = new Product("可乐", 5);
static final Product snack = new Product("零食", 3);
public static void main(String[] args) {
double totalMoney = 20; // 小明总钱数
int bookBought = 1; // 购买的书的数量
// 购买一本书后的花费
totalMoney -= book.price * bookBought;
System.out.println("小明购买了一本书,共花费:" + (book.price * bookBought));
// 遍历其他商品,找出剩余钱可以购买的商品及其最大数量
for (Product product : Arrays.asList(pencil, eraser, coke, snack)) {
if (totalMoney >= product.price) {
int itemsBuyable = (int) Math.floor(totalMoney / product.price); // 取整向下取
System.out.println("剩余的钱还可以购买" + product.name + ",可以购买" + itemsBuyable + "件,最后会剩下:" + ((double) totalMoney - (product.price * itemsBuyable)));
break; // 找到一个符合条件的商品就停止循环
}
}
}
}
```
运行这个程序后,你会看到小明购买完书后还能购买哪些商品,以及最多能买多少件,并计算出剩余的钱。
阅读全文
相关推荐


















