JAVA 基于字符串界面的收银台程序
一、展示
1.关于功能
2.设置功能
查看以往所有商品信息功能(在退出前需要保存所有商品信息!!!)
3.交互功能
查看以往订单信息功能(每次打印完订单需要保存!!!)
4.退出功能
二、思路分析
1.思路框图
2.思路详解
①把商品抽象为一个类Goods,属性为ID,name,price
②开一个仓库,即商品中心SimpleGoodsCenter.向商品中心添加商品add(),移除商品remove(),修改商品adjust(),清空商品clear(),获取商品信息getInfo(String id),打印商品中心所有商品的信息List(),打印某个ID号的商品信息getInfoList(ID)保存所有商品信息store(),调取(加载)商品信息load(),判断商品中心中该商品是否存在exists()
商品中心要new一个HashMap,用key储存商品编号,用value储存商品信息
③把订单抽象为一个类Order,商品中心作为商店,从商店中获取商品编号和数量.添加某商品的数量add(),移除某商品的数量rem(),订单列表信息ListInfo(),获取商品信息getInfo(),获取每个订单的价格getPrice(),
④开一个仓库,管理所有订单,即订单管理中心SimpleOrderCenter(),添加订单add(),移除订单cancel(),保存订单信息Ordersstore(),调取订单信息Ordersload(),打印订单信息列表list(),打印以往订单信息列表Findlist(),(list()和FindList()的不同之处在于变量订单编号是否自增),订单编号的保存idstore(),订单变好的加载idload(),
订单中心要new一个HashMap,用key储存商品编号,用value储存订单信息
⑤在主类中使用各种条件语句完成收银台功能
三、代码中用到的陌生函数
①判断输入是否包含汉字
public static boolean isHaveChinese(String str) {
boolean flag = true;
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count = count + 1;
}
}
if (count == 0) {
flag = false;
}
return flag;
}
② 调取时间的函数
new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").format(new Date())
③HashMap获取key 获取value
Set<Map.Entry<String, Order>> set = ordermap.entrySet();
Iterator<Map.Entry<String, Order>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Order> entry = iterator.next();
String ID = entry.getKey();
Order order = entry.getValue();
}
四、源代码
package com.wantto.shop;
import java.util.Arrays;
/**
* by:wby
*/
public class Goods {
private String ID = null;
private String name = null;
private double price = 0.0;
public Goods(String ID, String name, double price) {
this.ID = ID;
this.name = name;
this.price = price;
}
public Goods() {
}
public String getID() {
return ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
/*
* 通过商品编号获取商品信息
* */
public Goods getGoodInfo(String ID) {
return new Goods(ID, this.name, this.price);
}
@Override
public String toString() {
return String.format("%s %s %.2f", this.ID, this.name, this.price);
}
}
package com.wantto.shop;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* by:wby
*/
class SimpleGoodsCenter {
private static Map<String, Goods> goodmap = new HashMap<>();
/*
* 添加商品
* */
public void add(Goods good) {
goodmap.put(good.getID(), good);
}
/*
* 移除商品
* */
public void remove(String ID) {
goodmap.remove(ID);
}
/*
* 修改商品
* */
public void adjust(String ID, String name, double price) {
//写的不好!!!
Goods newgood = goodmap.get(ID);
newgood.setName(name);
newgood.setPrice(price);
goodmap.replace(ID, newgood);
}
/*
* 商品信息列表
* */
public String list() {
StringBuffer sb = new StringBuffer();
sb.append(" 商品清单\n").append("编号\t\t" + "名称\t\t" + "价格" + "\n");
for (Goods good : goodmap.values()) {
String[] str = good.toString().split(" ");
String ID = str[0];
String name = str[1];
double price = Double.parseDouble(str[2]);
sb.append(ID).append("\t\t").append(name).append("\t\t").append(price).append("\n");
}
return sb.toString();
}
/*
* 清除商品
* */
public void clear() {
// //想要删除文件中的所有商品信息
// File file = new File("E:" + File.separator + "GOODList" + File.separator + "Goodlist.txt");
// if(file.exists()&&file!=null){
// file.delete();
goodmap.clear();
}
/*
* 保存商品
* */
public void store() throws Exception {
File file = new File("E:" + File.separator + "GOODList" + File.separator + "Goodlist.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
OutputStream out = null;
for (Goods goods : goodmap.values()) {
String str = goods.toString();
// StringBuffer strs=new StringBuffer();
// strs.append(str+"\r\n");换行
//换行
String strs = str + System.getProperty("line.separator");
//如果没有true,现在的信息会覆盖之前的信息
out = new FileOutputStream(file, true);
out.write(strs.getBytes());
}
//如果没有商品,out为空,所以加以判断
out.close();
}
/*
* 加载商品信息
* */
public void load() throws Exception {
//定义文件路径
File file = new File("E:" + File.separator + "GOODList" + File.separator + "Goodlist.txt");
//定义输入流:一滴一滴的流
if (file.exists()) {
Reader rd = new FileReader(file);
//定义有缓冲的输入流,可以使用一行一行的读取,相当于一个管道
BufferedReader buf = new BufferedReader(rd);
String str = null;
//一行一行的读取
while ((str = buf.readLine()) != null) {
String[] res = str.split(" ");
Goods good = new Goods(res[0], res[1], Double.parseDouble(res[2]));
goodmap.put(good.getID(), good);
}
buf.close();
}
}
/*
*判断商品是否存在
* */
public boolean exists(String ID) {
return goodmap.containsKey(ID);
}
/*
* 通过商品编号获取商品信息
* */
public Goods getInfo(String ID) {
return goodmap.get(ID);
}
/*
* 通过商品编号获取单个商品信息
* */
public String getInfoList(String ID) {
StringBuffer sb = new StringBuffer();
sb.append("编号\t\t" + "名称\t\t" + "价格" + "\n");
Goods good = goodmap.get(ID);
String[] str = good.toString().split(" ");
String iD = str[0];
String name = str[1];
double price = Double.parseDouble(str[2]);
sb.append(iD).append("\t\t").append(name).append("\t\t").append(price).append("\n");
return sb.toString();
}
}
package com.wantto.shop;
import java.util.HashMap;
import java.util.Map;
/**
* by:wby
*/
class Order {
private static Map<String, Integer> order = new HashMap<>();
private static SimpleGoodsCenter goodsmap = null;
Order(SimpleGoodsCenter goodmap) {
goodsmap = goodmap;
}
/*
* 添加商品数量
* */
void add(String ID, Integer count) {
Integer num = order.get(ID);
if (num != null) {
num += count;
} else {
num = count;
}
order.put(ID, num);
}
/*
* 减少商品数量
* */
void rem(String ID, Integer count) {
Integer num = order.get(ID);
if (num != null) {
num -= count;
num = num > 0 ? num : 0;
} else {
num = 0;
}
order.replace(ID, num);
}
/*
* 通过商品编号获取商品信息
* */
Goods getInfo(String ID) {
return goodsmap.getInfo(ID);
}
/*
* 订单信息
* */
String listInfo(String ID) {
//商品名称 商品数量 商品单价 商品花费
//商品信息
Goods goodInfo = goodsmap.getInfo(ID);
StringBuffer sb = new StringBuffer();
sb.append(goodInfo.getName()).append("\t\t\t\t").append(order.get(ID)).append("\t\t\t").
append(goodInfo.getPrice()).append("\t\t\t").append(order.get(ID) * goodInfo.getPrice()).append("\n");
return sb.toString();
}
/*
* 订单花费
* */
double getPrice(String ID) {
Goods goodInfo = goodsmap.getInfo(ID);
return order.get(ID) * goodInfo.getPrice();
}
}
package com.wantto.shop;
import com.sun.xml.internal.bind.annotation.OverrideAnnotationOf;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
/**
* by:wby
*/
class SimpleOrderCenter {
private static Map<String, Order> ordermap = new HashMap<>();
static Integer orderId = 0;
public SimpleOrderCenter(int orderId) {
this.orderId = orderId;
}
/*
* 保存订单编号
* */
public void idstore() throws Exception {
File file = new File("E:" + File.separator + "GOODList" + File.separator + "orderid.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
OutputStream out = new FileOutputStream(file);
String str = String.valueOf(orderId);
StringBuffer strs = new StringBuffer();
//strs=strs.append(str+System.getProperty("line.separator"));
strs.append(str).append("\r\n");
out.write(strs.toString().getBytes());
out.close();
}
/*
* 加载订单编号
* */
public void idload() throws Exception {
//定义文件路径
File file = new File("E:" + File.separator + "GOODList" + File.separator + "orderid.txt");
if (file.exists()) {
InputStream in = new FileInputStream(file);
byte[] data = new byte[10];
int len = in.read(data);
orderId = Integer.parseInt(new String(data, 0, len).trim());
in.close();
}
}
/*
* 添加订单
* */
public void add(String ID, Order order) {
ordermap.put(ID, order);
}
/*
* 取消订单
* */
public void cancel(String ID) {
ordermap.remove(ID);
}
/*
* 订单信息列表
* */
public String list() throws Exception {
double totalPrice = 0;
StringBuffer sb = new StringBuffer();
sb.append("订单信息 " + new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").format(new Date()) + "\n");
sb.append("==========================================\n");
sb.append("商品名称").append("\t\t").append("商品数量").append("\t\t").append("商品单价").append("\t\t").
append("商品消费").append("\n").append("==========================================").append("\n");
Set<Map.Entry<String, Order>> set = ordermap.entrySet();
Iterator<Map.Entry<String, Order>> iterator = set.iterator();
totalPrice = getOrderInfo(totalPrice, sb, iterator);
sb.append("总计消费:" + totalPrice + "\n");
sb.append("==========================================\n");
//订单编号有问题
sb.append("打印编号:" + (++orderId) + "\n");
return sb.toString();
}
//重构,因为list和findList只有orderID不同,所以把其他相同的重构
public double getOrderInfo(double totalPrice, StringBuffer sb, Iterator<Map.Entry<String, Order>> iterator) {
while (iterator.hasNext()) {
Map.Entry<String, Order> entry = iterator.next();
String ID = entry.getKey();
Order order = entry.getValue();
String info = order.listInfo(ID);
double singlePrice = order.getPrice(ID);
totalPrice += singlePrice;
sb.append(info);
}
return totalPrice;
}
public String Findlist() throws Exception {
double totalPrice = 0;
StringBuffer sb = new StringBuffer();
sb.append("订单信息 " + new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").format(new Date()) + "\n");
sb.append("==========================================\n");
sb.append("商品名称").append("\t\t").append("商品数量").append("\t\t").append("商品单价").append("\t\t").
append("商品消费").append("\n").append("==========================================").append("\n");
Set<Map.Entry<String, Order>> set = ordermap.entrySet();
Iterator<Map.Entry<String, Order>> iterator = set.iterator();
totalPrice = getOrderInfo(totalPrice, sb, iterator);
sb.append("总计消费:" + totalPrice + "\n");
sb.append("==========================================\n");
sb.append("打印编号:" + (orderId) + "\n");
return sb.toString();
}
/*
* 加载以往订单查看功能
* */
public String OrdersLoad() throws Exception {
File file = new File("E:" + File.separator + "GOODList" + File.separator + "OrderMemory.txt");
// String str= null;
String strs = null;
if (file.exists()) {
InputStream in = new FileInputStream(file);
// Reader rd=new FileReader(file);
// BufferedReader buf=new BufferedReader(rd);
// while((str=buf.readLine())!=null){
// strs=str+"\n";
// }
byte[] data = new byte[1024];
int len = in.read(data);
strs = new String(data, 0, len);
in.close();
}
return strs.toString();
}
/*
* 保存以往订单信息
* */
public void Ordersstore() throws Exception {
//记录订单信息
File file = new File("E:" + File.separator + "GOODList" + File.separator + "OrderMemory.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file, true);
String str = this.Findlist() + "\r\n";
out.write(str.getBytes());
out.close();
}
}
package com.wantto.shop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* by:wby
*/
public class CheckStand {
private static Scanner scanner = new Scanner(System.in);
//打印编号
private static Integer orderId = 0;
//开辟清单的空间,否则没有内存运行,加载会出现NPE
private static SimpleGoodsCenter goods = new SimpleGoodsCenter();
private static Goods good = new Goods();
private static Order order = new Order(goods);
private static SimpleOrderCenter orders = new SimpleOrderCenter(orderId);
public static void menu() {
System.out.println(" 基于字符串界面的收银台 ");
System.out.println("==============================");
System.out.println(" [A]关于 [S]设置" +
"\n" + " [T]交互 [Q]退出");
System.out.println(" 使用 A S T Q进行操作");
System.out.println("==============================");
}
public static void settingInfo() {
System.out.println(" 设置功能");
System.out.println("==============================");
System.out.println(" [U]上架 [D]下架 [F]修改" +
"\n" + " [L]浏览商品 [C]清除商品\n" + " [R]返回上一级 " + " [S]保存商品");
System.out.println(" 使用用U D F L C R S进行操作");
System.out.println("==============================");
}
public static void useInfo() {
System.out.println(" 交互功能");
System.out.println("==============================");
System.out.println("[A]添加订单 [D]移除订单 [E]浏览订单" +
"\n" + "[G]浏览商品 [S]保存订单\n" + "[L]查看所有订单信息 " + "[R]返回上一级 ");
System.out.println(" 使用A D E G S L R进行操作");
System.out.println("==============================");
}
public static void about() {
System.out.println(" 关于功能");
System.out.println("==============================");
System.out.println("这是基于字符台界面的收银台系统V1.0 ");
System.out.println("==============================");
System.out.println(" 使用任意键进行返回操作");
}
public static void quiz() {
System.out.println(" 退出功能");
System.out.println("==============================");
System.out.println(" 离开本系统");
System.out.println(" ByeBye");
System.out.println("==============================");
System.exit(0);
}
public static void use() {
while (true) {
String in = scanner.nextLine();
switch (in.trim().toUpperCase()) {
case "A": {
while (true) {
System.out.println("请输入下单商品编号 数量");
String[] strs = scanner.nextLine().split(" ");
if (goods.getInfo(strs[0]) != null) {
System.out.println("下单成功");
order.add(strs[0], Integer.parseInt(strs[1]));
orders.add(strs[0], order);
useInfo();
break;
} else {
System.out.println("输入有误,请正确输入!!!");
}
}
break;
}
case "D": {
System.out.println("请输入取消订单的商品编号");
String str = scanner.nextLine();
if (goods.getInfo(str) != null) {
orders.cancel(str);
System.out.println("订单取消成功");
useInfo();
} else {
System.out.println("订单不存在!!!");
}
break;
}
case "E": {
try {
orders.idload();
System.out.println(orders.list());
orders.idstore();
useInfo();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case "L": {
try {
System.out.println(orders.OrdersLoad());
useInfo();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case "G": {
System.out.println(goods.list());
useInfo();
break;
}
case "R":
break;
case "S":
try {
orders.Ordersstore();
System.out.println("订单保存成功");
useInfo();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
useInfo();
}
if (in.toUpperCase().trim().equals("R")) {
menu();
break;
}
}
}
public static void setting() {
while (true) {
String in = scanner.nextLine();
switch (in.trim().toUpperCase()) {
case "U": {
while (true) {
System.out.println("请按照格式输入上架商品信息(商品编号 商品名称 商品价格)");
String[] str = scanner.nextLine().split(" ");
if (str.length == 3) {
if (goods.exists(str[0])) {
System.out.println("商品已存在,不能重复上架!!!");
} else {
if (isHaveChinese(str[2])) {
System.out.println("输入有误,价格应该为数值!!!");
} else {
good = new Goods(str[0], str[1], Double.parseDouble(str[2]));
goods.add(good);
System.out.println("上架成功");
settingInfo();
break;
}
}
} else {
System.out.println("请重新输入上架商品信息");
}
}
break;
}
case "D": {
System.out.println("请输入下架商品商品编号");
String str = scanner.nextLine();
if (goods.getInfo(str) != null) {
goods.remove(str);
System.out.println("商品下架成功");
settingInfo();
} else {
System.out.println("下架商品编号不存在,无法下架!!!");
}
break;
}
case "F": {
System.out.println("请按照格式修改商品信息(商品编号 商品名称 商品价格)");
String[] str = scanner.nextLine().split(" ");
System.out.println("修改前的商品信息");
if (goods.getInfo(str[0]) != null) {
System.out.println(goods.getInfoList(str[0]));
System.out.println("修改后的商品信息");
goods.adjust(str[0], str[1], Double.parseDouble(str[2]));
System.out.println(goods.getInfoList(str[0]));
settingInfo();
break;
} else {
System.out.println("商品不存在,无法修改!!!");
}
}
case "L": {
System.out.println(goods.list());
settingInfo();
break;
}
case "C": {
goods.clear();
settingInfo();
break;
}
case "R":
break;
case "S":
try {
goods.store();
settingInfo();
} catch (Exception e) {
e.printStackTrace();
}
break;
default:
settingInfo();
}
if (in.trim().toUpperCase().equals("R")) {
menu();
break;
}
}
}
// public static void StoreAll() {
// try {
// orders.idstore();
// orders.Ordersstore();
// goods.store();
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
public static void main(String[] args) throws Exception {
menu();
goods.load();
while (true) {
String input = scanner.nextLine();
switch (input.trim().toUpperCase()) {
case "A":
about();
break;
case "Q":
quiz();
break;
case "T":
useInfo();
use();
break;
case "S":
settingInfo();
setting();
break;
default:
menu();
}
}
}
/*
* 判断是否包含中文
* */
public static boolean isHaveChinese(String str) {
boolean flag = true;
int count = 0;
String regEx = "[\\u4e00-\\u9fa5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
while (m.find()) {
for (int i = 0; i <= m.groupCount(); i++) {
count = count + 1;
}
}
if (count == 0) {
flag = false;
}
return flag;
}
}