用ArrayList模拟实现一个购物车程序,实现商品的添加删除,计算总价等功能,Java程序
时间: 2024-02-22 08:54:43 浏览: 38
好的,以下是用ArrayList模拟实现购物车程序的Java代码:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class ShoppingCart {
public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<String>(); // 创建购物车,用ArrayList存储商品名称
double totalPrice = 0; // 初始化总价为0
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请选择要进行的操作:1.添加商品 2.删除商品 3.查看购物车 4.结算");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("请输入要添加的商品名称:");
String item = sc.next();
cart.add(item);
System.out.println("商品已成功添加到购物车!");
break;
case 2:
System.out.println("请输入要删除的商品名称:");
String delItem = sc.next();
if (cart.remove(delItem)) {
System.out.println("商品已成功从购物车中删除!");
} else {
System.out.println("购物车中不存在该商品!");
}
break;
case 3:
if (cart.isEmpty()) {
System.out.println("购物车为空!");
} else {
System.out.println("购物车中的商品有:");
for (String i : cart) {
System.out.println(i);
}
}
break;
case 4:
if (cart.isEmpty()) {
System.out.println("购物车为空,请先添加商品!");
} else {
for (String i : cart) {
totalPrice += 10; // 假设每个商品价格为10元
}
System.out.println("购物车中的商品总价为:" + totalPrice + "元");
System.out.println("欢迎再次光临!");
System.exit(0); // 结束程序
}
break;
default:
System.out.println("输入有误,请重新输入!");
break;
}
}
}
}
```
以上程序中,用ArrayList存储购物车中的商品名称,用一个变量totalPrice存储商品总价,每次添加商品时向ArrayList中添加商品名称,每次删除商品时从ArrayList中删除商品名称,每次查看购物车时遍历ArrayList打印所有商品名称,每次结算时遍历ArrayList计算商品总价。其中使用了Scanner类实现用户输入。