这个购物车用了个简单的Map集合
package com.sxt;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
class Goods{
private Integer id;
private String name;
private Integer price;
private Integer numbers;
Goods(){}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getNumbers() {
return numbers;
}
public void setNumbers(Integer numbers) {
this.numbers = numbers;
}
public Goods(Integer id, String name, Integer price, Integer numbers) {
super();
this.id = id;
this.name = name;
this.price = price;
this.numbers = numbers;
}
}
public class MyGwcDemo {
Map<Integer,Goods> al=new HashMap<Integer,Goods>();
//添加购物车
public void cun() {
Scanner sc=new Scanner(System.in);
System.out.println("请输入商品的ID");
Integer id = sc.nextInt();
Goods m=new Goods();
if(al.containsKey(id)) {
al.get(id).setNumbers((al.get(id).getNumbers()+1));
}else {
m.setId(id);
System.out.println("请输入商品的名字");
String name = sc.next();
m.setName(name);
System.out.println("请输入商品的价格");
int jia = sc.nextInt();
m.setPrice(jia);
m.setNumbers(1);
al.put(id, m);
}
// sc.close();
}
//查看一件
public void cha() {
System.out.println("请输入要查看商品的ID");
Scanner sc=new Scanner(System.in);
Integer id = sc.nextInt();
System.out.println("Id\t名字\t价格\t数量");
System.out.println(al.get(id).getId()+"\t"+al.get(id).getName()+"\t"+al.get(id).getPrice()+"\t"+al.get(id).getNumbers());
//sc.close();
}
//删除商品
public void deleate(){
System.out.println("请输入要删除的商品的ID");
Scanner sc=new Scanner(System.in);
Integer id = sc.nextInt();
al.remove(id);
//sc.close();
}
//查看购物车
public void View() {
for(Goods g:al.values()) {
System.out.println("Id\t名字\t价格\t数量");
System.out.println(g.getId()+"\t"+g.getName()+"\t"+g.getPrice()+"\t"+g.getNumbers());
}
}
public static void main(String[] args) {
MyGwcDemo myg=new MyGwcDemo();
//Scanner sc =new Scanner(System.in);
Scanner sc =new Scanner(System.in);
do {
System.out.println("1.添加商品\t 2.查看商品\t 3.删除商品 \t 4.查看所有商品\t 5.退出");
Integer it = sc.nextInt();
switch(it) {
case 1: myg.cun();
break;
case 2:myg.cha();
break;
case 3:myg.deleate();
break;
case 4:myg.View();
break;
case 5:
sc.close();
System.exit(0);
default:System.out.println("输入有误,请重新输入");
break;
}
}while(true);
}
}