用Java写一个购物单程序
时间: 2023-05-13 09:04:34 浏览: 99
用Java写的一个购物系统
好的,以下是一个简单的Java购物单程序:
import java.util.Scanner;
public class ShoppingList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] items = {"苹果", "香蕉", "橙子", "西瓜", "葡萄"};
double[] prices = {2.5, 3.0, 2.8, 5.0, 4.5};
int[] amounts = new int[5];
double total = 0.0;
System.out.println("欢迎使用购物单程序!");
while (true) {
System.out.println("请选择商品编号(1-5),输入0结束:");
int choice = scanner.nextInt();
if (choice == 0) {
break;
}
if (choice < 1 || choice > 5) {
System.out.println("输入有误,请重新输入!");
continue;
}
System.out.println("请输入购买数量:");
int amount = scanner.nextInt();
amounts[choice - 1] += amount;
total += amount * prices[choice - 1];
}
System.out.println("您的购物清单如下:");
for (int i = 0; i < 5; i++) {
if (amounts[i] > 0) {
System.out.println(items[i] + " x " + amounts[i] + ",单价:" + prices[i] + "元");
}
}
System.out.println("总计:" + total + "元");
System.out.println("感谢使用购物单程序!");
}
}
您可以根据需要进行修改和扩展。
阅读全文