Java:購物綜合案例,收銀系統(tǒng),查看所有顧客,所有商品 ,用戶購買商品 ,單個顧客信息

/*購物綜合案例:
收銀系統(tǒng):功能1.查看所有顧客 2.查看所有商品 3.用戶購買商品 4.查看單個顧客信息(含常見錯誤分析講解圖片)*/






package a;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
//顧客類:
class guke {
HashSet<shangpin> h = new HashSet<shangpin>();// 是顧客的商品列表
int yonghudeID;
String yonghuname;
// 在構(gòu)造方法中對顧客的屬性進行賦值,商品不能賦值,因為還沒有買商品:
public guke(int iD, String name) {
yonghudeID = iD;
this.yonghuname = name;
}
// 購買商品的方法:
public void mai(int shurudeshangpinbianhao) {
h.add(lizi.shangpinshuzu.get(shurudeshangpinbianhao - 1));
}
//
@Override
public String toString() {
return "用戶的ID:" + yonghudeID + ", 用戶的名字:" + yonghuname;
}
}
public class lizi {
// 顧客的集合:
static ArrayList<guke> gukeshuzu = new ArrayList<guke>();
// 定義商品集合:
static ArrayList<shangpin> shangpinshuzu = new ArrayList<shangpin>();
public static void main(String[] args) {
gukeshuzu.add(new guke(1, "張三"));
gukeshuzu.add(new guke(2, "李四"));
gukeshuzu.add(new guke(3, "王五"));
shangpinshuzu.add(new shangpin(1, "蘋果", 3.5));
shangpinshuzu.add(new shangpin(2, "香蕉", 2.5));
shangpinshuzu.add(new shangpin(3, "橘子", 4.5));
shangpinshuzu.add(new shangpin(4, "巧克力", 5.5));
shangpinshuzu.add(new shangpin(5, "果汁", 6.5));
System.out.println("-------詩書畫唱收銀系統(tǒng)--------");
while (true) {
System.out.println("請選擇你要執(zhí)行的功能:1.查看所有顧客? ?2.查看所有商品? "
+ "3.用戶購買商品? 4.查詢單個顧客的購買信息");
Scanner s = new Scanner(System.in);
int num = s.nextInt();
if (num == 1) {
// 查詢所有顧客:
for (int i = 0; i < gukeshuzu.size(); i++) {
System.out.println(gukeshuzu.get(i));
}
} else if (num == 2) {
// 查詢所有商品:
Iterator i = shangpinshuzu.iterator();
while (i.hasNext()) {
shangpin sh = (shangpin) i.next();
sh.say();
}
} else if (num == 3) {
// 購物:
System.out.println("請輸入用戶的編號");
int shurudeyonghubianhao = s.nextInt();
for (int i = 0; i < gukeshuzu.size(); i++) {
if (shurudeyonghubianhao == gukeshuzu.get(i).yonghudeID) {
while (true) {
System.out.println(gukeshuzu.get(i).yonghuname
+ ",請選擇你要購買的商品的編號");
int shurudeshangpinbianhao = s.nextInt();
gukeshuzu.get(i).mai(shurudeshangpinbianhao);
// mai(shurudeshangpinbianhao)是定義買的方法進行購買商品
System.out.println("購買成功,是否繼續(xù)購買?1.繼續(xù)? 2.不買了");
int sss = s.nextInt();
if (sss == 2) {
break;
}
}
}
}
} else if (num == 4) {
// 查詢用戶的商品:
// 查詢所有顧客:
System.out.println("請輸入你要查詢的顧客的編號");
int biaohao = s.nextInt();
for (int i = 0; i < gukeshuzu.size(); i++) {
if (gukeshuzu.get(i).yonghudeID == biaohao) {
if (gukeshuzu.get(i).h.isEmpty()) {
System.out.println("你還沒有購買商品");
} else {
Iterator j = gukeshuzu.get(i).h.iterator();
while (j.hasNext()) {
shangpin w = (shangpin) j.next();
w.say();
}
}
}
}
}
}
}
}
// 商品類
class shangpin {
int bianhao;
String name;
double price;
// 構(gòu)造方法中對其賦值:
public shangpin(int bianhao, String name, double price) {
this.bianhao = bianhao;
this.name = name;
this.price = price;
}
// 商品介紹:
public void say() {
System.out.println("編號:" + this.bianhao +
"\t名稱:" + this.name + "\t價格"
+ this.price);
}
}







