赞
踩
这是跟韩老师做的一个满汉楼项目,是一个餐馆的管理系统。运用到的技术是Java基础编程,jdbc,Mysql,界面采用控制台。结构采用分层设计。
功能如下:
员工登录—>预定餐桌—>显示菜单—>点菜—>查看账单—>结账—>员工退出登录
当然有不少细节和逻辑判断,比如说预定餐桌,如果该桌是已预订或者正在用餐,那么这一桌是不可选的。比如说点餐,菜品必须要在菜单内,也不能给不存在的餐桌号点餐,在用餐的餐桌不能被其他用户预定,状态设置为“用餐中”。结账,需要在点餐时生成账单,初始化为“未支付”;结账后更新状态,并且把该餐桌的状态设置为“空”。
创建的表:
注意导入相关jar包
和写配置文件
,这些是简化jdbc开发,操作数据库的jar包。
数据库表:
create table employee (
id int primary key auto_increment,
empId varchar(50) not null default '',
pwd char(32) not null default '',
name varchar(50) not null default '',
job varchar(50) not null default ''
)charset=utf8;
#测试数据
insert into employee values(null, '666666', md5('123456'), '小谢', '经理');
以员工表为例,注意设置id为主键
并自增长
。其他表格类似,字段可以看javabean。建表的sql语句没有保存,放一张示意。
登录
显示餐桌状态
预定餐桌
显示所有菜品
点餐服务
查看账单
结账
此时的订单支付状态和餐桌状态已自动更新:
退出满汉楼
package com.serein.view; import com.serein.domain.*; import com.serein.service.BillService; import com.serein.service.DiningTableService; import com.serein.service.EmployeeService; import com.serein.service.MenuService; import com.serein.utils.Utility; import java.util.List; public class MHLView { private boolean loop = true;//loop控制循环是否结束 private String key = ""; //以下创建对象,以便调用service的方法完成业务逻辑处理,体现了面向对象编程思想 private EmployeeService employeeService = new EmployeeService(); private DiningTableService diningTableService = new DiningTableService(); private MenuService menuService = new MenuService(); private BillService billService = new BillService(); //主方法,启动页面 public static void main(String[] args) { new MHLView().mainMenu(); } //结账服务 public void payBill(){ System.out.println("==========结账服务==========="); System.out.print("请选择要结账的餐桌编号(-1退出):"); int diningTableId = Utility.readInt(); if (diningTableId == -1){ System.out.println("==========取消结账==========="); return; } //根据餐桌号判断要结账的餐桌号是否存在 DiningTable diningTable = diningTableService.getDiningTableById(diningTableId); if (diningTable == null){ System.out.println("==========结账的餐桌号不存在==========="); return; } //判断该餐桌上有没有没结账的菜品 if (!billService.hasPayBillByDiningTableId(diningTableId)){ System.out.println("==========该餐位没有未结账的账单==========="); return; } System.out.print("支付方式(支付宝/微信/现金)(回车退出):"); String payMode = Utility.readString(20, ""); //防止误操作,再给用户一次取消的机会 if ("".equals(payMode)){ System.out.println("==========取消结账==========="); return; } char key = Utility.readConfirmSelection(); if (key == 'Y'){ if (billService.payBill(diningTableId,payMode)){ System.out.println("==========完成结账==========="); }else { System.out.println("==========结账失败==========="); } }else { System.out.println("==========取消结账==========="); } } //查看菜单 public void listBill(){ // List<Bill> bills = billService.list(); // System.out.println("\n编号\t\t菜品号\t\t菜品量\t\t金额\t\t桌号\t\t日期\t\t\t\t\t\t\t状态"); // for (Bill bill : bills) { // System.out.println(bill); // } // System.out.println("=======显示完毕======="); List<MultiTableBean> multiTableBeans = billService.list2(); System.out.println("\n编号\t\t菜品号\t\t菜品量\t\t金额\t\t桌号\t\t日期\t\t\t\t\t\t\t状态\t\t菜品名"); for (MultiTableBean bill : multiTableBeans) { System.out.println(bill); } System.out.println("=======显示完毕======="); } //点餐 public void orderMenu(){ System.out.println("==========点餐服务==========="); System.out.print("请输入点餐的桌号(-1退出):"); int orderDiningTableId = Utility.readInt(); if (orderDiningTableId == -1){ System.out.println("==========取消点餐==========="); return; } System.out.print("请输入点餐的菜品号(-1退出):"); int orderMenuId = Utility.readInt(); if (orderMenuId == -1){ System.out.println("==========取消点餐==========="); return; } System.out.print("请输入点餐的菜品量(-1退出):"); int orderNums = Utility.readInt(); if (orderNums == -1){ System.out.println("==========取消点餐==========="); return; } //判断餐桌号是否存在 DiningTable diningTable = diningTableService.getDiningTableById(orderDiningTableId); if (diningTable == null){ System.out.println("==========餐桌号不存在==========="); return; } //判断有没有这个菜 Menu menu = menuService.getMenuById(orderMenuId); if (menu == null){ System.out.println("==========该菜品编号不存在==========="); return; } //调用点餐的方法,并完成该方法后,会返回一个boolean值。 if (billService.orderMenu(orderMenuId,orderNums,orderDiningTableId)){ System.out.println("==========点餐成功==========="); }else { System.out.println("==========点餐失败==========="); } } //显示菜品 public void listMenu(){ List<Menu> list = menuService.list(); System.out.println("\n菜品编号\t\t菜品名\t\t菜品类别\t\t价格"); for (Menu menu : list) { System.out.println(menu); } System.out.println("======显示菜品完毕======"); } //订座 public void orderDiningTable(){ System.out.println("===========预定餐桌============="); System.out.println("请输入要预定的餐桌编号(-1退出):"); int orderId = Utility.readInt(); if (orderId == -1){ System.out.println("===========取消预定============="); return; } char key = Utility.readConfirmSelection(); if (key == 'Y'){ DiningTable diningTable = diningTableService.getDiningTableById(orderId); if (diningTable == null){ System.out.println("===========预定餐桌不存在============="); return; } if (!("空".equals(diningTable.getState()))){ System.out.println("===========预定餐桌已预订或正在就餐中============="); return; } System.out.print("预订人的名字:"); String orderName = Utility.readString(50); System.out.print("预订人的电话号码:"); String orderTel = Utility.readString(50); //订座会调用专门的方法,该方法执行完后会返回一个boolean值 if (diningTableService.orderDiningTable(orderId,orderName,orderTel)){ System.out.println("===========预定餐桌成功============="); }else { System.out.println("===========预定餐桌失败============="); } }else { System.out.println("===========取消预定============="); } } //显示所有餐桌的状态,据此知道哪些是空桌 public void listDiningTable(){ List<DiningTable> list = diningTableService.list(); System.out.println("\n餐桌编号\t\t餐桌状态"); for (DiningTable diningTable : list) { System.out.println(diningTable); } System.out.println("======显示完毕======="); } //页面,即逻辑框架 public void mainMenu(){ while (loop){ System.out.println("================满汉楼=================="); System.out.println("\t\t 1 登录满汉楼"); System.out.println("\t\t 2 退出满汉楼"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key){ case "1": System.out.print("请输入员工工号:"); String empId = Utility.readString(50); System.out.print("请输入密码:"); String pwd = Utility.readString(50); Employee employee = employeeService.getEmployeeByIdAndPwd(empId, pwd); if (employee != null){ System.out.println("================登录成功[" + employee.getName() + "]==================\n"); //二级菜单 while (loop){ System.out.println("\n================满汉楼(二级菜单)=================="); System.out.println("\t\t 1 显示餐桌状态"); System.out.println("\t\t 2 预定餐桌"); System.out.println("\t\t 3 显示所有菜品"); System.out.println("\t\t 4 点餐服务"); System.out.println("\t\t 5 查看账单"); System.out.println("\t\t 6 结账"); System.out.println("\t\t 9 退出满汉楼"); System.out.print("请输入你的选择:"); key = Utility.readString(1); switch (key){ case "1": listDiningTable(); break; case "2": orderDiningTable(); break; case "3": listMenu(); break; case "4": orderMenu(); break; case "5": listBill(); break; case "6": payBill(); break; case "9": loop = false; break; default: System.out.println("你的输入有误,请重新输入:"); break; } } }else { System.out.println("================登录失败=================="); } break; case "2": loop = false; break; default: System.out.println("你输入有误,请重新输入"); } } System.out.println("你已退出满汉楼系统..."); } }
package com.serein.service; import com.serein.dao.BillDAO; import com.serein.dao.MultiTableDAO; import com.serein.domain.Bill; import com.serein.domain.MultiTableBean; import java.util.List; import java.util.UUID; public class BillService { //以下是创建相关对象,以便调用其属性和方法。 //创建对象,然后用这个对象来做事,体现了面向对象编程思想 private BillDAO billDAO = new BillDAO(); private MenuService menuService = new MenuService(); private DiningTableService diningTableService = new DiningTableService(); private MultiTableDAO multiTableDAO = new MultiTableDAO(); //点餐的方法 public boolean orderMenu(int menuId,int nums,int diningTableId){ //用Java的api为每份账单生成一个如ccd503a5-66f5-432c-879d-14bdf676f09a这样的高位数菜单,避免账单号重复混淆 String billID = UUID.randomUUID().toString(); //点一个菜自动生成一份账单 int update = billDAO.update("insert into bill values(null,?,?,?,?,?,now(),'未结账')", billID, menuId, nums, menuService.getMenuById(menuId).getPrice() * nums, diningTableId); //未加入账单,说明点菜失败 if (update <= 0){ return false; } //已成功点菜,把餐桌状态设置为就餐中 return diningTableService.updateDiningTableState(diningTableId,"就餐中"); } //查询账单 public List<Bill> list(){ return billDAO.queryMulti("select * from bill",Bill.class); } //查询账单,联合菜单表多表查询,在显示菜单的时候也显示对应菜名。是上一个方法的升级版 public List<MultiTableBean> list2(){ return multiTableDAO.queryMulti("select bill.*,name from bill,menu where bill.menuId = menu.id",MultiTableBean.class); } //判断某张餐桌是否有没结账的账单(一菜一单) public boolean hasPayBillByDiningTableId(int diningTableId){ Bill bill = billDAO.querySingle("select * from bill where diningTableId =? and state = '未结账' limit 0,1", Bill.class, diningTableId); return bill != null; } //完成结账 public boolean payBill(int diningTableId,String payMode){ //给未结账的餐桌安排结账 int update = billDAO.update("update bill set state = ? where diningTableId = ? and state = '未结账'", payMode, diningTableId); //结账失败 if (update <= 0){ return false; } //把这张餐桌的状态设置为“空”,若没有置空则说明结账流程没走完,失败 if (!diningTableService.updateDiningTableToFree(diningTableId,"空")){ return false; } //上述两步都走完了,说明结账成功了 return true; } }
package com.serein.service; import com.serein.dao.DiningTableDAO; import com.serein.domain.DiningTable; import java.util.List; public class DiningTableService { //创建EmployeeDAO实例,以便调用其方法操作数据库。 private DiningTableDAO diningTableDAO = new DiningTableDAO(); //查询餐桌的状态,返回一个集合 public List<DiningTable> list(){ return diningTableDAO.queryMulti("select id,state from diningTable",DiningTable.class); } //根据餐桌号得到该餐桌对象,以便查看该餐桌的属性,例如该餐桌是否被预定是否在使用 public DiningTable getDiningTableById(int id){ return diningTableDAO.querySingle("select * from diningTable where id = ?", DiningTable.class,id); } //预定餐桌调用该方法,把餐桌状态置为“已经预定” public boolean orderDiningTable(int id,String orderName,String orderTel){ int update = diningTableDAO.update("update diningTable set state = '已经预定',orderName = ?,orderTel = ? where id = ?", orderName, orderTel,id); return update > 0; } //改变餐桌的状态 public boolean updateDiningTableState(int id,String state){ int update = diningTableDAO.update("update diningTable set state=? where id=?", state, id); return update > 0; } //根据餐桌号把餐桌的状态置为“空” public boolean updateDiningTableToFree(int id,String state){ int update = diningTableDAO.update("update diningTable set state=?,orderName='',orderTel='' where id=?", state, id); return update > 0; } }
package com.serein.service; import com.serein.dao.EmployeeDAO; import com.serein.domain.Employee; public class EmployeeService { //创建EmployeeDAO实例,以便调用其方法操作数据库。 private EmployeeDAO employeeDAO = new EmployeeDAO(); //判断登录的账号密码是否和数据库的数据匹配 //返回值不为null说明在数据库查到了,即账号合法。 public Employee getEmployeeByIdAndPwd(String empId, String pwd){ Employee employee = employeeDAO.querySingle("select * from employee where empId = ? and pwd = md5(?)", Employee.class, empId, pwd); return employee; } }
package com.serein.service; import com.serein.dao.MenuDAO; import com.serein.domain.Menu; import java.util.List; public class MenuService { private MenuDAO menuDAO = new MenuDAO(); //得到菜单并封装到集合 public List<Menu> list(){ return menuDAO.queryMulti("select * from menu",Menu.class); } //根据菜品编号得到菜品对象,以便调用它的价格,数量等属性。 public Menu getMenuById(int id){ return menuDAO.querySingle("select * from menu where id = ?",Menu.class,id); } }
package com.serein.dao; import com.serein.utils.JDBCUtilsByDruid; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class BasicDAO<T> { //泛型指定具体类型 private QueryRunner qr = new QueryRunner(); //开发通用的dml方法, 针对任意的表 public int update(String sql, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); int update = qr.update(connection, sql, parameters); return update; } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //返回多个对象(即查询的结果是多行) public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //查询单行结果 的通用方法 public T querySingle(String sql, Class<T> clazz, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //查询单行单列的方法,即返回单值的方法 public Object queryScalar(String sql, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new ScalarHandler(), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } }
package com.serein.dao;
import com.serein.domain.Bill;
//继承BasicDAO即可,约束泛型,有特有属性方法可以补充
public class BillDAO extends BasicDAO<Bill>{
}
package com.serein.dao;
import com.serein.domain.DiningTable;
//继承BasicDAO即可,约束泛型,有特有属性方法可以补充
public class DiningTableDAO extends BasicDAO<DiningTable>{
}
package com.serein.dao;
import com.serein.domain.Employee;
//继承BasicDAO即可,约束泛型,有特有属性方法可以补充
public class EmployeeDAO extends BasicDAO<Employee>{
}
package com.serein.dao;
import com.serein.domain.Menu;
//继承BasicDAO即可,约束泛型,有特有属性方法可以补充
public class MenuDAO extends BasicDAO<Menu>{
}
package com.serein.dao;
import com.serein.domain.MultiTableBean;
//继承BasicDAO即可,约束泛型,有特有属性方法可以补充
public class MultiTableDAO extends BasicDAO<MultiTableBean>{
}
package com.serein.domain; import java.util.Date; public class Bill { private Integer id; private String billId; private Integer menuId; private Integer nums; private Double money; private Integer diningTableId; private Date billDate; private String state; public Bill() { } public Bill(Integer id, String billId, Integer menuId, Integer nums, Double money, Integer diningTableId, Date billDate, String state) { this.id = id; this.billId = billId; this.menuId = menuId; this.nums = nums; this.money = money; this.diningTableId = diningTableId; this.billDate = billDate; this.state = state; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBillId() { return billId; } public void setBillId(String billId) { this.billId = billId; } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public Integer getNums() { return nums; } public void setNums(Integer nums) { this.nums = nums; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public Integer getDiningTableId() { return diningTableId; } public void setDiningTableId(Integer diningTableId) { this.diningTableId = diningTableId; } public Date getBillDate() { return billDate; } public void setBillDate(Date billDate) { this.billDate = billDate; } public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public String toString() { return id + "\t\t" + menuId + "\t\t\t" + nums + "\t\t\t" + money + "\t" + diningTableId + "\t\t" + billDate + "\t\t" + state; } }
package com.serein.domain; public class DiningTable { private Integer id; private String state; private String orderName; private String orderTel; public DiningTable() { } public DiningTable(Integer id, String state, String orderName, String orderTel) { this.id = id; this.state = state; this.orderName = orderName; this.orderTel = orderTel; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public String getOrderTel() { return orderTel; } public void setOrderTel(String orderTel) { this.orderTel = orderTel; } @Override public String toString() { return id + "\t\t\t" + state; } }
package com.serein.domain; public class Employee { private Integer id; private String empId; private String pwd; private String name; private String job; public Employee() { } public Employee(Integer id, String empId, String pwd, String name, String job) { this.id = id; this.empId = empId; this.pwd = pwd; this.name = name; this.job = job; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } }
package com.serein.domain; public class Menu { private Integer id; private String name; private String type; private Double price; public Menu() { } public Menu(Integer id, String name, String type, Double price) { this.id = id; this.name = name; this.type = type; this.price = price; } 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 String getType() { return type; } public void setType(String type) { this.type = type; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Override public String toString() { return id + "\t\t\t" + name + "\t\t" + type + "\t\t" + price; } }
package com.serein.domain; import java.util.Date; /** * 这个类并不是对应某一张数据库表,而是综合了两张表的属性。 * 目的是可以进行多表查询 */ public class MultiTableBean { private Integer id; private String billId; private Integer menuId; private Integer nums; private Double money; private Integer diningTableId; private Date billDate; private String state; private String name; public MultiTableBean() { } public MultiTableBean(Integer id, String billId, Integer menuId, Integer nums, Double money, Integer diningTableId, Date billDate, String state, String name) { this.id = id; this.billId = billId; this.menuId = menuId; this.nums = nums; this.money = money; this.diningTableId = diningTableId; this.billDate = billDate; this.state = state; this.name = name; } public String getBillId() { return billId; } public void setBillId(String billId) { this.billId = billId; } public Integer getMenuId() { return menuId; } public void setMenuId(Integer menuId) { this.menuId = menuId; } public Integer getNums() { return nums; } public void setNums(Integer nums) { this.nums = nums; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } public Integer getDiningTableId() { return diningTableId; } public void setDiningTableId(Integer diningTableId) { this.diningTableId = diningTableId; } public Date getBillDate() { return billDate; } public void setBillDate(Date billDate) { this.billDate = billDate; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public String toString() { return id + "\t\t" + menuId + "\t\t\t" + nums + "\t\t\t" + money + "\t" + diningTableId + "\t\t" + billDate + "\t\t" + state + "\t\t" + name; } }
package com.serein.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.FileInputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtilsByDruid { private static DataSource ds; static { Properties properties = new Properties(); try { properties.load(new FileInputStream("D:\\code\\mhl\\src\\com\\serein\\druid.properties")); ds = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException(e); } } public static Connection getConnection() throws SQLException { return ds.getConnection(); } public static void close(ResultSet resultSet, Statement statement, Connection connection) { try { if (resultSet !=null){ resultSet.close(); } if (statement != null){ statement.close(); } if (connection != null){ connection.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
package com.serein.utils; /** 工具类的作用: 处理各种情况的用户输入,并且能够按照程序员的需求,得到用户的控制台输入。 */ import java.util.Scanner; /** */ public class Utility { //静态属性。。。 private static Scanner scanner = new Scanner(System.in); /** * 功能:读取键盘输入的一个菜单选项,值:1——5的范围 * @return 1——5 */ public static char readMenuSelection() { char c; for (; ; ) { String str = readKeyBoard(1, false);//包含一个字符的字符串 c = str.charAt(0);//将字符串转换成字符char类型 if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5') { System.out.print("选择错误,请重新输入:"); } else break; } return c; } /** * 功能:读取键盘输入的一个字符 * @return 一个字符 */ public static char readChar() { String str = readKeyBoard(1, false);//就是一个字符 return str.charAt(0); } /** * 功能:读取键盘输入的一个字符,如果直接按回车,则返回指定的默认值;否则返回输入的那个字符 * @param defaultValue 指定的默认值 * @return 默认值或输入的字符 */ public static char readChar(char defaultValue) { String str = readKeyBoard(1, true);//要么是空字符串,要么是一个字符 return (str.length() == 0) ? defaultValue : str.charAt(0); } /** * 功能:读取键盘输入的整型,长度小于2位 * @return 整数 */ public static int readInt() { int n; for (; ; ) { String str = readKeyBoard(10, false);//一个整数,长度<=10位 try { n = Integer.parseInt(str);//将字符串转换成整数 break; } catch (NumberFormatException e) { System.out.print("数字输入错误,请重新输入:"); } } return n; } /** * 功能:读取键盘输入的 整数或默认值,如果直接回车,则返回默认值,否则返回输入的整数 * @param defaultValue 指定的默认值 * @return 整数或默认值 */ public static int readInt(int defaultValue) { int n; for (; ; ) { String str = readKeyBoard(10, true); if (str.equals("")) { return defaultValue; } //异常处理... try { n = Integer.parseInt(str); break; } catch (NumberFormatException e) { System.out.print("数字输入错误,请重新输入:"); } } return n; } /** * 功能:读取键盘输入的指定长度的字符串 * @param limit 限制的长度 * @return 指定长度的字符串 */ public static String readString(int limit) { return readKeyBoard(limit, false); } /** * 功能:读取键盘输入的指定长度的字符串或默认值,如果直接回车,返回默认值,否则返回字符串 * @param limit 限制的长度 * @param defaultValue 指定的默认值 * @return 指定长度的字符串 */ public static String readString(int limit, String defaultValue) { String str = readKeyBoard(limit, true); return str.equals("")? defaultValue : str; } /** * 功能:读取键盘输入的确认选项,Y或N * 将小的功能,封装到一个方法中. * @return Y或N */ public static char readConfirmSelection() { System.out.println("请输入是否确定(Y/N): "); char c; for (; ; ) {//无限循环 //在这里,将接受到字符,转成了大写字母 //y => Y n=>N String str = readKeyBoard(1, false).toUpperCase(); c = str.charAt(0); if (c == 'Y' || c == 'N') { break; } else { System.out.print("选择错误,请重新输入:"); } } return c; } /** * 功能: 读取一个字符串 * @param limit 读取的长度 * @param blankReturn 如果为true ,表示 可以读空字符串。 * 如果为false表示 不能读空字符串。 * * 如果输入为空,或者输入大于limit的长度,就会提示重新输入。 * @return */ private static String readKeyBoard(int limit, boolean blankReturn) { //定义了字符串 String line = ""; //scanner.hasNextLine() 判断有没有下一行 while (scanner.hasNextLine()) { line = scanner.nextLine();//读取这一行 //如果line.length=0, 即用户没有输入任何内容,直接回车 if (line.length() == 0) { if (blankReturn) return line;//如果blankReturn=true,可以返回空串 else continue; //如果blankReturn=false,不接受空串,必须输入内容 } //如果用户输入的内容大于了 limit,就提示重写输入 //如果用户如的内容 >0 <= limit ,我就接受 if (line.length() < 1 || line.length() > limit) { System.out.print("输入长度(不能大于" + limit + ")错误,请重新输入:"); continue; } break; } return line; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。