java实现一个简单的购物车

这个购物车用了个简单的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);
		
	}
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值