1. 程式人生 > >Java電子商城專案控制檯版(面向物件版)

Java電子商城專案控制檯版(面向物件版)

 

 

基於面向物件的方式程式設計

根據商城選單分析如下的物件的內容:

物件 屬性 行為
使用者 使用者名稱和密碼 註冊,登入,購買,檢視
管理員 使用者名稱和密碼 新增,修改,刪除
商城

當前登入使用者

管理員

商品集合

使用者集合

掃描器

顯示選單的方法

獲取使用者輸入的選單

判斷使用者輸入的選單

商品 編號,名稱,價格,數量  

User類:

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Scanner;
/**
 * User
 * 這個been類實現了Serializable這個介面(實現檔案讀寫(序列化))
 * 所具有的屬性:使用者名稱,密碼
 * 所具有的行為:註冊,登入,購買,檢視
 * @author 
 *
 */
public class User implements Serializable{
	String username;
	String userpwd;
	Goods goods = new Goods();
	//驗證是否登入
	private boolean isLogin;
	
	
	public boolean isLogin() {
		return isLogin;
	}

	public void setLogin(boolean isLogin) {
		this.isLogin = isLogin;
	}

	/*
	 * 校驗使用者名稱合法性
	 */
	private boolean checkUsername(String username) {
		//定義一個為false的bool值
		boolean res = false;
		//使用者名稱長度不滿6位,則重新輸入
		if (username.length() != 6) {
			System.out.println("使用者名稱長度必須為6位");
			return res;
		} else if (Character.isDigit(username.charAt(0))) {//使用者名稱不能以數字開頭,則重新輸入
			System.out.println("使用者名稱不能以數字開頭");
			return res;
		} else {
			//成功,返回true,繼續下一步操作
			return res = true;
		}
	}
	
	/*
	 * 購買商品的方法
	 */
	public void buy() {
		while (true) {
			System.out.println("請選擇您需要購買商品的編號:");
			int id = Shop.sc.nextInt();
			System.out.println("您將要的購買的商品資訊如下:");
			Goods shopGoods = this.findGoodsById(id);
			System.out.println(shopGoods);
			System.out.println("請輸入您需要購買商品的數量:");
			int num = Shop.sc.nextInt();

			Goods myGoods = new Goods();
//			myGoods.setId(shopGoods.getId());
//			myGoods.setName(shopGoods.getName());
//			myGoods.setPrice(shopGoods.getPrice());
			//通過clone()方法,就省去了以上備註釋的內容
			myGoods = shopGoods.clone();
			myGoods.setNum(num);
			//將已選擇的商品新增到我的商品集合中
			Shop.myGoodsList.add(myGoods);
			System.out.println("是否繼續Y/N");
			String choice = Shop.sc.next();
			choice = choice.toUpperCase();
			if (choice.equals("N")) {
				break;
			}
		}
		this.showMyGoodsList();
	}
	/*
	 * 展示已購買的商品資訊
	 */
	private void showMyGoodsList() {
		System.out.println("******您購買的商品列表如下******");
		BigDecimal total = new BigDecimal("0");
		for (Goods myGoods : Shop.myGoodsList) {
			System.out.println(myGoods);
			//將在buy()方法中儲存的資訊提取出來,獲取商品的價格
			BigDecimal price = myGoods.getPrice();
			//獲取商品的數量
			int num = myGoods.getNum();
			//計算
			total = total.add(price.multiply(new BigDecimal(num)));
			//total = total.add(myGoods.getPrice().multiply(new BigDecimal(myGoods.getNum())));
		}
		System.out.println("總價格為:" + total);
	}
	/*
	 * 註冊方法
	 */
	public void registUser() {
		//校驗使用者名稱合法性的標識
		boolean isCheck = true;

		while (true) {
			System.out.println("歡迎註冊");
			System.out.println("請輸入使用者名稱");
			Shop.sc = new Scanner(System.in);
			String rusername = Shop.sc.next();
			//校驗結果的返回值
			isCheck = this.checkUsername(rusername);

			System.out.println(isCheck);

			if (isCheck == true) {
				System.out.println("請輸入密碼");
				String ruserpwd = Shop.sc.next();
				System.out.println("請再次輸入密碼");
				String reuserpwd = Shop.sc.next();
				if (ruserpwd.equals(reuserpwd)) {
					User user = new User();
					user.setUsername(rusername);
					user.setUserpwd(ruserpwd);
					Shop.userList.add(user);
					System.out.println("註冊成功");
					//使用者註冊成功則將使用者的註冊資訊儲存到Userfile檔案中
					Shop.saveListToFile();
					break;
				} else {
					System.out.println("密碼不一致請重新輸入");
				}
			}
		}

	}
	/*
	 * 登入方法
	 */
	public void login() {
		boolean loginResult = false;
		int maxTime = 0;
		while (true) {
			if (maxTime != 3) {
				maxTime++;
				System.out.println("歡迎登入");
				System.out.println("請輸入使用者名稱");
				Shop.sc = new Scanner(System.in);
				String username = Shop.sc.next();
				System.out.println("請輸入密碼");
				String userpwd = Shop.sc.next();
				for (User user : Shop.userList) {
					if (username.equals(user.username) && userpwd.equals(user.userpwd)) {
						System.out.println("登入成功");
						this.setLogin(true);
						loginResult = true;
						break;
					}
				}
				if (loginResult == true) {
					break;
				} else {
					if (maxTime != 3) {
						System.out.println("登入失敗賬號或密碼有誤,請重新登入");
					}
				}

			} else {
				System.out.println(maxTime + "次登入失敗,系統退出");
				System.exit(0);
			}

		}
	}
	/*
	 * 展示商品資訊
	 */
	public void showGoodsList() {
		System.out.println("******商品列表如下******");
//		Shop.readGoods2File();
//		for (Goods goods : Shop.goodsList) {
//			System.out.println(goods);
//		}
		goods.initGoodsList();
		
	}
	/*
	 * 查詢商品的方法
	 */
	public Goods findGoodsById(int id) {

		Goods returnGoods = null;
		for (Goods goods : Shop.goodsList) {
			if (goods.getId() == id) {
				returnGoods = goods;
				break;
			}
		}
		return returnGoods;
	}

	public User() {
		super();
	}

	public User(String username, String userpwd) {
		super();
		this.username = username;
		this.userpwd = userpwd;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUserpwd() {
		return userpwd;
	}

	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}

}

Admin類:

import java.math.BigDecimal;
/**
 * Admin
 * 這個been類繼承了User(Admin為User的子類)
 * 所具有的屬性:使用者名稱和密碼
 * 所具有的行為:新增,修改,刪除
 * @author 
 *
 */
public class Admin extends User {
	/*
	 * 管理員登入
	 */
	public void adminLogin() {

		System.out.println("歡迎管理員登入");
		System.out.println("請輸入管理員賬號");
		String admin = Shop.sc.next();
		while (true) {
			System.out.println("請輸入管理員密碼");
			String password = Shop.sc.next();
			if (admin.equals("admin") && password.equals("123456")) {
				System.out.println("管理員登入成功");
				while (true) {
					int choice = this.showAdminMenu();

					if (choice == 5) {
						break;
					}

					this.choiceAdminMenu(choice);
				}
				break;
			} else {
				System.out.println("登入失敗");
			}
		}
	}
	/*
	 * 展示管理員選單
	 */
	public int showAdminMenu() {
		System.out.println("*****************歡迎進入管理員選單**************");
		System.out.println("\t1.新增商品");
		System.out.println("\t2.修改商品");
		System.out.println("\t3.刪除商品");
		System.out.println("\t4.檢視商品列表");
		System.out.println("\t5.退出");
		System.out.println("******************************************");
		System.out.print("請選擇選單:");
		int choice = Shop.sc.nextInt();
		return choice;
	}
	/*
	 * 判斷是否繼續的方法
	 */
	public String isGo_on() {
		System.out.println("您是否繼續:Y/N");
		String go_on = Shop.sc.next();
		return go_on.toUpperCase();
	}
	/*
	 * 選單選擇方法
	 */
	public boolean choiceAdminMenu(int choice) {
		boolean result = true;
		String go_on = "Y";
		switch (choice) {
		case 1:
			System.out.println("你選擇的是新增商品");
			//當go_on為Y時,則繼續執行新增商品操作
			while (go_on.equals("Y")) {
				this.addGoods();
				go_on = this.isGo_on();
			}
			break;
		case 2:
			System.out.println("你選擇的是修改商品");
			this.updateGoods();
			break;
		case 3:
			System.out.println("你選擇的是刪除商品");
			this.deleteGoods();
			break;
		case 4:
			System.out.println("你選擇的是檢視商品列表");
			super.showGoodsList();
			break;
		case 5:
			System.out.println("退出");
			result = false;
			break;
		default:
			System.out.println("輸入有誤");
			break;
		}
		return false;
	}
	/*
	 * 刪除商品方法
	 */
	public void deleteGoods() {
		System.out.println("****開始修改商品資訊****");
		System.out.println("請輸入要修改的商品編號:");
		int id = Shop.sc.nextInt();
		Goods goods = super.findGoodsById(id);
		Shop.goodsList.remove(goods);
		System.out.println("商品刪除成功");
		Shop.saveGoods2File();
	}
	/*
	 * 修改商品方法
	 */
	public void updateGoods() {
		System.out.println("****開始修改商品資訊****");
		System.out.println("請輸入要修改的商品編號:");
		int id = Shop.sc.nextInt();
		Goods goods = super.findGoodsById(id);
		
		if (goods == null) {
			System.out.println("未找到該商品");
		} else {
		
			System.out.println("商品資訊如下:");
			System.out.println("商品編號\t商品名稱\t商品價格\t商品數量\t");
			System.out.println(
					goods.getId() + "\t" + goods.getName() + "\t" + goods.getPrice() + "\t" + goods.getNum() + "\t");
		}
		System.out.println("請輸入修改後的商品名稱:");
		String name = Shop.sc.next();
		goods.setName(name);
		System.out.println("請輸入修改後的商品價格:");
		double price = Shop.sc.nextDouble();
		goods.setPrice(new BigDecimal(price));
		System.out.println("請輸入修改後的商品數量:");
		int num = Shop.sc.nextInt();
		goods.setNum(num);
		Shop.saveGoods2File();
	}

	
	/*
	 * 新增商品方法
	 */
	public void addGoods() {

		System.out.println("****開始新增商品****");
		System.out.println("請輸入商品編號:");
		int id = Shop.sc.nextInt();
		System.out.println("請輸入商品名稱:");
		String name = Shop.sc.next();
		System.out.println("請輸入商品價格:");
		String price = Shop.sc.next();
		System.out.println("請輸入商品數量:");
		int num = Shop.sc.nextInt();

		Goods goods = new Goods();
		goods.setId(id);
		goods.setName(name);
		goods.setPrice(new BigDecimal(price));
		goods.setNum(num);
		Shop.goodsList.add(goods);
		System.out.println("商品新增成功");
		Shop.saveGoods2File();
	}

	
}

Shop類:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
 * 商城類
 * 所具有的屬性:當前登入使用者,管理員,商品集合,使用者集合,掃描器
 * 所具有的行為:顯示選單的方法,獲取使用者輸入的選單,判斷使用者輸入的選單
 * @author 
 *
 */
public class Shop {
	//定義一個全域性變數的掃描i去,用於使用者輸出
	static Scanner sc = new Scanner(System.in);
	//定義一個goodsList容器存放商品資訊
	static List<Goods> goodsList = new ArrayList<Goods>();
	//定義一個myGoodsList容器存購買的放商品資訊
	static List<Goods> myGoodsList = new ArrayList<Goods>();
	//定義一個userList容器存放使用者資訊
	static List<User> userList = new ArrayList<User>();
	static File userFile = new File("E:\\workspace2\\ConsolShop1.8\\src\\com\\test\\shop\\Userfile");
	static File goodsFile = new File("E:\\workspace2\\ConsolShop1.8\\src\\com\\test\\shop\\Goodsfile");
	User user = new User();
	Admin admin = new Admin();
	Goods goods = new Goods();
	
	public static void saveGoods2File(){
		try {
			FileOutputStream fos = new FileOutputStream(goodsFile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(goodsList);
			oos.close();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void readGoods2File(){
		try {
			FileInputStream fis = new FileInputStream(goodsFile);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Object obj = ois.readObject();
			goodsList = (List) obj;
			ois.close();
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void saveListToFile(){
		try {
			FileOutputStream fos = new FileOutputStream(userFile);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(userList);
			oos.close();
			fos.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void readListFromFile(){
		try {
			FileInputStream fis = new FileInputStream(userFile);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Object obj = ois.readObject();
			userList = (List) obj;
			ois.close();
			fis.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static void main(String[] args) {
		Shop shop = new Shop();
		shop.run();
	}
	
	private void run() {
		this.readListFromFile();
		//設定一個是否退出的條件
		boolean isBreak = true;
		while (isBreak) {
			int choice = this.showMenu();
			//當choice選擇為6事,返回的值為false,同時將值賦給了isBreak,並退出選單
			isBreak = this.chooseMenu(choice);
		}
	}
	
	/*
	 * 選單展示
	 */
	private int showMenu() {
		System.out.println("*****************歡迎進入電子商城**************");
		System.out.println("\t1.註冊");
		System.out.println("\t2.登入");
		System.out.println("\t3.檢視商城");
		System.out.println("\t4.檢視我購買的商品(我的購物車)");
		System.out.println("\t5.管理員登入");
		System.out.println("\t6.退出系統");
		System.out.println("******************************************");
		System.out.print("請選擇選單:");
		int choice = sc.nextInt();
		return choice;
	}
	
	/*
	 * 選單選擇
	 */
	private boolean chooseMenu(int choice) {
		boolean result = true;
		switch (choice) {
		case 1:
			System.out.println("你選擇的選單是:註冊");
			user.registUser();
			break;
		case 2:
			System.out.println("你選擇的選單是:登入");
			user.login();
			break;
		case 3:
			System.out.println("你選擇的選單是:檢視商城");
			goods.initGoodsList();
			//判斷使用者是否登入
			if(user.isLogin() == true){//成功登入,則可以進行購買操作
				user.buy();
			}else{
				System.out.println("你還未登入,請先登入,在購買商品");
			}
			break;
		case 4:
			System.out.println("你選擇的選單是:檢視我購買的商品(我的購物車)");
			break;
		case 5:
			System.out.println("管理員登入");
			admin.adminLogin();
			break;
		case 6:
			System.out.println("謝謝使用");
			result = false;
			break;
		default:
			System.out.println("輸入有誤");
			break;
		}
		return result;
	}
	
	
}

Goods類:

import java.io.Serializable;
import java.math.BigDecimal;
/**
 * Goods
 * 這個been類需要先實現Comparable, Cloneable, Serializable這三個介面
 * 分別意思為:實現排序方法,實現clone物件方法,實現檔案讀寫(序列化)
 * 所具有的屬性:編號,名稱,價格,數量
 * @author 
 *
 */
public class Goods implements Comparable, Cloneable, Serializable {
	private int id;
	private String name;
	private BigDecimal price;
	private int num;
	
	/**
	 * 重寫clone方法
	 */
	public Goods clone(){
		Goods g1 = new Goods();
		try {
			g1 = (Goods) super.clone();
		} catch (CloneNotSupportedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return g1;
	}
	/*
	 * 初始化商品
	 */
	public void initGoodsList() {
		Goods goods1 = new Goods(1, "iPhone7Plus", new BigDecimal("4999"), 5);
		Goods goods2 = new Goods(2, "iPhone8Plus", new BigDecimal("6999"), 10);
		Goods goods3 = new Goods(3, "iPhoneXMax", new BigDecimal("11999"), 25);
		//將商品資訊新增到商品集合中
		Shop.goodsList.add(goods1);
		Shop.goodsList.add(goods2);
		Shop.goodsList.add(goods3);
		//迴圈遍歷顯示商品資訊
		for (Goods goods : Shop.goodsList) {
			System.out.println(goods);
		}
		//讀取Goodsfile中的商品資訊到控制檯
		Shop.readGoods2File();
	}

	public Goods() {
		super();
	}

	public Goods(int id, String name, BigDecimal price, int num) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.num = num;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return "[id = " + id + ",name = " + name + ",price = " + price + ",num = " + num + "]";
	}

	// 商品的排序
	@Override
	public int compareTo(Object o) {
		Goods goods = (Goods) o;
		// if(this.num < goods.num){
		// //小於
		// return -1;
		// } else if(this.num == goods.num){
		// //等於
		// return 0;
		// } else{
		// //大於
		// return 1;
		// }
		return this.compareTo(goods.price);
	}
}