java超市购物程序代码
时间: 2023-10-14 08:35:13 浏览: 78
以下是一个简单的 Java 超市购物程序代码示例:
```java
import java.util.Scanner;
public class Supermarket {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 商品清单
String[] products = {"苹果", "香蕉", "饮料", "面包", "牛奶"};
double[] prices = {3.5, 2.8, 4.0, 5.0, 2.0};
// 购物车
String[] cartProducts = new String[100];
double[] cartPrices = new double[100];
int cartCount = 0;
// 显示商品清单
System.out.println("欢迎光临超市!");
for (int i = 0; i < products.length; i++) {
System.out.println((i+1) + ". " + products[i] + " " + prices[i] + "元");
}
// 购物过程
int choice;
do {
System.out.print("请选择要购买的商品编号(输入0结束购物):");
choice = scanner.nextInt();
if (choice >= 1 && choice <= products.length) {
cartProducts[cartCount] = products[choice-1];
cartPrices[cartCount] = prices[choice-1];
cartCount++;
System.out.println(products[choice-1] + "已添加到购物车!");
} else if (choice != 0) {
System.out.println("没有该商品,请重新选择!");
}
} while (choice != 0);
// 显示购物清单
System.out.println("购物清单:");
double totalPrice = 0.0;
for (int i = 0; i < cartCount; i++) {
System.out.println(cartProducts[i] + " " + cartPrices[i] + "元");
totalPrice += cartPrices[i];
}
System.out.println("总计:" + totalPrice + "元");
scanner.close();
}
}
```
该程序使用数组来存储商品清单和购物车中的商品信息,使用循环和条件语句实现购物过程,并在购物结束后计算出总价并输出购物清单。可以根据实际需求对程序进行修改和扩展。
阅读全文