【Java】基礎_14_開發團隊排程系統

IT界小小小學生發表於2020-12-01


1.介紹

增刪查,普通員工不要,用instanceof判斷物件型別
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
如下檢視類和管理類分析
在這裡插入圖片描述
Javabean實體類與Data類分析,如下員工型別分析
在這裡插入圖片描述
如下員工數量分析
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

2.人

package com.atguigu.bean;

public class Employee {
	private int id;
	private String name;
	private int age;
	private double salary;
	public Employee(int id, String name, int age, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.salary = salary;
	}
	public Employee() {
		super();
	}
	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 int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	/*
ID     	姓名      年齡    		工資     	 職位      狀態      獎金     		 股票    	領用裝置
 1      段譽      22        3000.0
 2      令狐沖  32        18000.0  架構師  FREE  15000.0  2000    聯想T4(6000.0)
 3      任我行  23        7000.0   程式設計師  FREE                   戴爾(NEC17寸)
 4      張三丰  24        7300.0   程式設計師  FREE                   戴爾(三星 17寸)
 5      周芷若  28        10000.0  設計師  FREE  5000.0           佳能 2900(鐳射)
	 */
	@Override
	public String toString() {
		return getBasicInfo();
	}
	protected String getBasicInfo() {
		return id + "\t" + name + "\t" + age + "\t" + salary;
	}	
}
package com.atguigu.bean;

public class Programmer extends Employee {
	private int memberId;//團隊編號     在加入到團隊時,才開始分配,不是建立物件時分配
	private Status status = Status.FREE;
	private Equipment equipment;
	public Programmer() {
		super();
	}
	// 如下是有參構造
	public Programmer(int id, String name, int age, double salary, int memberId, Status status, Equipment equipment) {
		super(id, name, age, salary);
		this.memberId = memberId;
		this.status = status;
		this.equipment = equipment;
	}
	public Programmer(int id, String name, int age, double salary, Equipment equipment) { //Date.java中可看到
		super(id, name, age, salary);
		this.equipment = equipment;
	}
	public int getMemberId() {
		return memberId;
	}
	public void setMemberId(int memberId) {
		this.memberId = memberId;
	}
	public Status getStatus() {
		return status;
	}
	public void setStatus(Status status) {
		this.status = status;
	}
	public Equipment getEquipment() {
		return equipment;
	}
	public void setEquipment(Equipment equipment) {
		this.equipment = equipment;
	}
	/*
ID     	姓名      年齡    		工資     	 職位      狀態      獎金     		 股票    	領用裝置
 1      段譽      22        3000.0
 2      令狐沖  32        18000.0  架構師  FREE  15000.0  2000    聯想T4(6000.0)
 3      任我行  23        7000.0   程式設計師  FREE                   戴爾(NEC17寸)
 4      張三丰  24        7300.0   程式設計師  FREE                   戴爾(三星 17寸)
 5      周芷若  28        10000.0  設計師  FREE  5000.0           佳能 2900(鐳射)
	 */
	@Override
	public String toString() {
		return getBasicInfo()  +"\t程式設計師\t" + status + "\t\t\t" + equipment;
	}

	/*
TID/ID  姓名    年齡    	工資    	職位    	獎金   		 股票
 2/4    張三丰  24      7300.0  程式設計師
 3/2   	 令狐沖  32      18000.0 架構師 	15000.0 2000
 4/6    趙敏    22      6800.0  程式設計師
 5/12   黃蓉    27      9600.0  設計師        4800.0
	 */
	public String getMemberInfo(){
		return memberId + "/" + getBasicInfo() +"\t程式設計師";
	}
}
package com.atguigu.bean;

public interface Equipment {
	String getDescription();
}
package com.atguigu.bean;

public enum Status {
	BUSY,FREE,VOCATION
}
package com.atguigu.bean;

public class Designer extends Programmer{
	private double bonus;

	public Designer() {
		super();
	}

	public Designer(int id, String name, int age, double salary, Equipment equipment, double bonus) {
		super(id, name, age, salary, equipment);
		this.bonus = bonus;
	}

	public Designer(int id, String name, int age, double salary, int memberId, Status status, Equipment equipment,
			double bonus) {
		super(id, name, age, salary, memberId, status, equipment);
		this.bonus = bonus;
	}

	public double getBonus() {
		return bonus;
	}

	public void setBonus(double bonus) {
		this.bonus = bonus;
	}
	
	/*
ID     	姓名      年齡    		工資     	 職位      狀態      獎金     		 股票    	領用裝置
 1      段譽      22        3000.0
 2      令狐沖  32        18000.0  架構師  FREE  15000.0  2000    聯想T4(6000.0)
 3      任我行  23        7000.0   程式設計師  FREE                   戴爾(NEC17寸)
 4      張三丰  24        7300.0   程式設計師  FREE                   戴爾(三星 17寸)
 5      周芷若  28        10000.0  設計師  FREE  5000.0           佳能 2900(鐳射)
	 */
	@Override
	public String toString() {
		return getBasicInfo() + "\t設計師\t" + getStatus() + "\t" + bonus +"\t\t" + getEquipment();
	}
	
	/*
TID/ID  姓名    年齡    	工資    	職位    	獎金   		 股票
 2/4    張三丰  24      7300.0  程式設計師
 3/2   	 令狐沖  32      18000.0 架構師 	15000.0 2000
 4/6    趙敏    22      6800.0  程式設計師
 5/12   黃蓉    27      9600.0  設計師        4800.0
	 */
	public String getMemberInfo(){
		return getMemberId() + "/" + getBasicInfo() +"\t設計師\t" + bonus;
	}	
}
package com.atguigu.bean;

public class Architect extends Designer{
	private int stock;

	public Architect() {
		super();
	}

	public Architect(int id, String name, int age, double salary, Equipment equipment, double bonus, int stock) {
		super(id, name, age, salary, equipment, bonus);
		this.stock = stock;
	}

	public Architect(int id, String name, int age, double salary, int memberId, Status status, Equipment equipment,
			double bonus, int stock) {
		super(id, name, age, salary, memberId, status, equipment, bonus);
		this.stock = stock;
	}

	public int getStock() {
		return stock;
	}

	public void setStock(int stock) {
		this.stock = stock;
	}

	/*
ID     	姓名      年齡    		工資     	 職位      狀態      獎金     		 股票    	領用裝置
 1      段譽      22        3000.0
 2      令狐沖  32        18000.0  架構師  FREE  15000.0  2000    聯想T4(6000.0)
 3      任我行  23        7000.0   程式設計師  FREE                   戴爾(NEC17寸)
 4      張三丰  24        7300.0   程式設計師  FREE                   戴爾(三星 17寸)
 5      周芷若  28        10000.0  設計師  FREE  5000.0           佳能 2900(鐳射)
	 */
	@Override
	public String toString() {
		return getBasicInfo() + "\t架構師\t" + getStatus() + "\t" + getBonus() +"\t" +stock+ "\t" + getEquipment();
	}
	/*
TID/ID  姓名    年齡    	工資    	職位    	獎金   		 股票
 2/4    張三丰  24      7300.0  程式設計師
 3/2   	 令狐沖  32      18000.0 架構師 	15000.0 2000
 4/6    趙敏    22      6800.0  程式設計師
 5/12   黃蓉    27      9600.0  設計師        4800.0
	 */
	public String getMemberInfo(){
		return getMemberId() + "/" + getBasicInfo() +"\t架構師\t" + getBonus() + "\t" + stock;
	}	
}

3.物

package com.atguigu.bean;

public interface Equipment {
	String getDescription();
}
package com.atguigu.bean;

public class PC implements Equipment{
	private String model;
	private String display;
	public PC(String model, String display) {
		super();
		this.model = model;
		this.display = display;
	}
	public PC() {
		super();
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public String getDisplay() {
		return display;
	}
	public void setDisplay(String display) {
		this.display = display;
	}
	@Override
	public String toString() {
		return getDescription();
	}
	@Override
	public String getDescription() {
		// 戴爾(NEC17寸),model指品牌
		return model + "(" + display + ")" ;
	}	
}
package com.atguigu.bean;

public class NoteBook implements Equipment{
	private String model;
	private double price;
	public NoteBook(String model, double price) {
		super();
		this.model = model;
		this.price = price;
	}
	public NoteBook() {
		super();
	}
	public String getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model = model;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return getDescription();
	}
	@Override
	public String getDescription() {
		// 聯想T4(6000.0)
		return model + "(" + price + ")";
	}	
}
package com.atguigu.bean;

public class Printer implements Equipment{
	private String type;
	private String name;
	public Printer(String type, String name) {
		super();
		this.type = type;
		this.name = name;
	}
	public Printer() {
		super();
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public String toString() {
		return getDescription();
	}
	@Override
	public String getDescription() {
		//佳能 2900(鐳射)
		return name + "(" + type + ")";
	}
	
}

4.服務端

package com.atguigu.service;

import static com.atguigu.utils.Data.ARCHITECT;
import static com.atguigu.utils.Data.DESIGNER;
import static com.atguigu.utils.Data.EMPLOYEE;
import static com.atguigu.utils.Data.EMPLOYEES;
import static com.atguigu.utils.Data.EQIPMENTS;
import static com.atguigu.utils.Data.NOTEBOOK;
import static com.atguigu.utils.Data.PC;
import static com.atguigu.utils.Data.PRINTER;
import static com.atguigu.utils.Data.PROGRAMMER;

import com.atguigu.bean.Architect;
import com.atguigu.bean.Designer;
import com.atguigu.bean.Employee;
import com.atguigu.bean.Equipment;
import com.atguigu.bean.NoteBook;
import com.atguigu.bean.PC;
import com.atguigu.bean.Printer;
import com.atguigu.bean.Programmer;
import com.atguigu.exception.TeamException;

public class NameListService {
	private Employee[] all;//用來儲存全公司的員工物件
	
	public NameListService(){
		init();
	}
	
	//初始all陣列的方法,資料的來源是Data.java
	private void init(){
		//(1)建立all陣列,並指定長度,原本Date.EMPLOYEES.length,導包後省略Date.
		all = new Employee[EMPLOYEES.length];
		
		//(2)遍歷Data中EMPLOYEES的二維陣列,把一行一行的資料
		//封裝為一個一個的Employee,Programmer等的物件,放到all陣列中
		for (int i = 0; i < EMPLOYEES.length; i++) {
			//EMPLOYEES[i][0]是員工型別
			int empType = Integer.parseInt(EMPLOYEES[i][0]);
			
			//因為每一種員工,都有id,name,age,salary,所以這些資料的讀取轉換,放在switch的上面
			//EMPLOYEES[i][1]是員工編號id
			int id = Integer.parseInt(EMPLOYEES[i][1]);
			
			//EMPLOYEES[i][2]是員工姓名name
			String name = EMPLOYEES[i][2];
			
			//EMPLOYEES[i][3]是員工年齡age
			int age = Integer.parseInt(EMPLOYEES[i][3]);
			
			//EMPLOYEES[i][4]是員工薪資salary
			double salary = Double .parseDouble(EMPLOYEES[i][4]);
			
			switch(empType){
			case EMPLOYEE: //應該是Data.EMPLOYEE,因為有靜態匯入所以省略Data.
//				all[i] = 建立Employee物件;
				all[i] = new Employee(id, name, age, salary);
				break;
			case PROGRAMMER:
//				all[i] = 建立Programmer物件;getEquipmentByLineNumber(i)得到一個裝置物件
				all[i] = new Programmer(id, name, age, salary, getEquipmentByLineNumber(i));
				break;	
			case DESIGNER:
//				all[i] = 建立Designer物件;
				//EMPLOYEES[i][5]
				double bonus = Double.parseDouble(EMPLOYEES[i][5]);
				all[i] = new Designer(id, name, age, salary, getEquipmentByLineNumber(i), bonus);
				break;
			case ARCHITECT:
//				all[i] = 建立Architect物件;
				bonus = Double.parseDouble(EMPLOYEES[i][5]);
				int stock = Integer.parseInt(EMPLOYEES[i][6]);
				all[i] = new Architect(id, name, age, salary, getEquipmentByLineNumber(i), bonus, stock);
				break;			
			}
		}
	}
	
	//讀取第i行的裝置物件
	private Equipment getEquipmentByLineNumber(int i){
		//(1)讀取裝置的型別,即EQIPMENTS[i][0]
		int eType = Integer.parseInt(EQIPMENTS[i][0]);
		switch(eType){
		case PC:
			return new PC(EQIPMENTS[i][1], EQIPMENTS[i][2]);
		case NOTEBOOK:
			return new NoteBook(EQIPMENTS[i][1], Double.parseDouble(EQIPMENTS[i][2]));
		case PRINTER:
			return new Printer(EQIPMENTS[i][1], EQIPMENTS[i][2]);
		}
		return null;
	}

	//返回所有的員工物件
	public Employee[] getAll(){
		return all;
	}

	//根據員工編號,獲取員工物件
	public Employee getEmployeeById(int id) throws TeamException{
		for (int i = 0; i < all.length; i++) {
			if(all[i].getId() == id){
				return all[i];
			}
		}
		throw new TeamException(id+"對應的員工不存在");
	}
}
package com.atguigu.service;

import java.util.Arrays;

import com.atguigu.bean.Architect;
import com.atguigu.bean.Designer;
import com.atguigu.bean.Employee;
import com.atguigu.bean.Programmer;
import com.atguigu.bean.Status;
import com.atguigu.exception.TeamException;

public class TeamService {
	//因為開發團隊,要求必須是程式設計師、設計師、架構師
	private Programmer[] team;//用來裝開發團隊的成員
	private int total;//記錄實際開發團隊的成員的數量
	private static final int MAX_MEMBER = 5;
	private int currentMemberId = 1;//只增不減
	
	public TeamService(){
		team = new Programmer[MAX_MEMBER];
	}
	
	//新增一個團隊成員
	public void addMember(Employee emp) throws TeamException{
		//(1)判斷總人數
		if(total >= MAX_MEMBER){
			throw new TeamException("成員已滿,無法新增");
		}
		
		//(2)判斷是否是程式設計師或它子類的物件
		if(!(emp instanceof Programmer)){
			throw new TeamException("該成員不是開發人員,無法新增");
		}
		
		//(3)判斷狀態
		//如果要獲取狀態資訊,需要把emp物件向下轉型
		Programmer p = (Programmer) emp;
		switch(p.getStatus()){
		case BUSY:
			throw new TeamException("該員已是團隊成員");
		case VOCATION:
			throw new TeamException("該員正在休假,無法新增");
		}
		
		//(4)判斷每一種人的人數
		//現統計當前team中的每一個型別的物件的人數
		int pCount = 0;//程式設計師人數
		int dCount = 0;//設計師人數
		int aCount = 0;//架構師人數
		
		//這裡用total,有幾個人統計幾個人
		for (int i = 0; i < total; i++) {
			//條件判斷有順序要求
			if(team[i] instanceof Architect){
				aCount++;
			}else if(team[i] instanceof Designer){
				dCount++;
			}else{
				pCount++;
			}
		}
		
		//如果剛才傳入的emp-->p,是架構師,我們再看架構師夠不夠
		//如果剛才傳入的emp-->p,是設計師,我們再看設計師夠不夠
		//如果剛才傳入的emp-->p,是程式設計師,我們再看程式設計師夠不夠
		if(emp instanceof Architect ){
			if(aCount >= 1){
				throw new TeamException("團隊中只能有一名架構師");
			}
		}else if(emp instanceof Designer ){
			if(dCount >= 2){
				throw new TeamException("團隊中只能有兩名設計師");
			}
		}else{
			if(pCount >= 3){
				throw new TeamException("團隊中只能有三名程式設計師");
			}
		}
		
		//(5)可以正常新增
		//新增之前,修改狀態,分配團隊編號
		p.setStatus(Status.BUSY);
		p.setMemberId(currentMemberId++);
		//新增到team陣列
		team[total++] = p;
	}
	
	//返回所有團隊成員的方法
	public Programmer[] getAllMembers(){
		return Arrays.copyOf(team, total);
	}

	//根據團隊編號刪除團隊成員
	public void removeMemberByTid(int tid) throws TeamException{
		//(1)要查詢tid成員對應的下標index
		int index = -1;
		//這裡用total,有幾個人判斷幾個人
		for (int i = 0; i < total; i++) {
			if(team[i].getMemberId() == tid){
				index = i;
				break;
			}
		}
		if(index == -1){
			throw new TeamException(tid + "的團隊成員不存在!");
		}
		
		//(2)先修改要被刪除的成員的一些資訊
		//team[index]這個成員要被刪除
		team[index].setStatus(Status.FREE);
		team[index].setMemberId(0);
		
		//(3)把index後面的元素往前移動
		/*
		 * 如果記不住,如何推斷
		 * 第一個引數:原陣列
		 * 第二個引數:從哪個開始移動
		 * 第三個引數:目標陣列
		 * 第四個引數:第二個引數的下標的元素移動到哪個下標,例如:index+1位置的元素移動到index
		 * 第五個引數:一共移動幾個
		 * 
		 * 假設total = 5個,刪除index= 1位置的元素
		 * 移動[2]->[1],[3]->[2],[4]->[3]  3個  =total - index - 1
		 */
		System.arraycopy(team, index+1, team, index, total-index-1);
		
		//(4)把最後一個置為null
		team[total--] = null;//使得這個物件儘快被回收,騰出記憶體		
	}
}

5.客戶端

package com.atguigu.view;

import com.atguigu.bean.Employee;
import com.atguigu.bean.Programmer;
import com.atguigu.exception.TeamException;
import com.atguigu.service.NameListService;
import com.atguigu.service.TeamService;
import com.atguigu.utils.TSUtility;

public class TeamView {
	private NameListService ns = new NameListService();
	private TeamService ts = new TeamService();
	
	public void menu(){
		System.out.println("-------------------------------------開發團隊排程軟體--------------------------------------");
		getAllEmployee();
		
		while(true){
			System.out.println("---------------------------------------------------------------------------------------------------");
			System.out.print("1-團佇列表  2-新增團隊成員  3-刪除團隊成員 4-退出   請選擇(1-4):");
			char select = TSUtility.readMenuSelection();
			switch(select){
			case '1':
				list();
				break;
			case '2':
				getAllEmployee();
				add();
				break;
			case '3':
				list();
				remove();
				break;
			case '4':
				System.out.print("確認是否退出(Y/N):");
				char confirm = TSUtility.readConfirmSelection();
				if(confirm == 'Y'){
					return;
				}
			}
		}
	}
	
	private void remove() {
		System.out.println("---------------------刪除成員---------------------");
		//(1)輸入要刪除的團隊成員的團隊編號
		System.out.print("請輸入要刪除員工的TID:");
		int tid = TSUtility.readInt();
		
		//(2)確認是否刪除
		System.out.print("確認是否刪除(Y/N):");
		char confirm = TSUtility.readConfirmSelection();
		if(confirm == 'N'){
			System.out.println("刪除取消!");
			return;//提前結束刪除
		}
		
		try {
			//(3)刪除,呼叫TeamService的removeMemberByTid刪除
			ts.removeMemberByTid(tid);
			System.out.println("刪除成功!");
		} catch (TeamException e) {
			System.out.println("刪除失敗,原因:" + e.getMessage());
		}
		
		TSUtility.readReturn();
	}

	private void add() {
		System.out.println("---------------------新增成員---------------------");
		//(1)輸入編號
		System.out.print("請輸入要新增的員工ID:");
		int id = TSUtility.readInt();
		
		//(2)根據編號獲取員工物件
		try {
			Employee emp = ns.getEmployeeById(id);
			
			//(3)新增到團隊中
			
			ts.addMember(emp);
			
			System.out.println("新增成功");
		} catch (TeamException e) {
			System.out.println("新增失敗,原因:" + e.getMessage());
		}
		
		TSUtility.readReturn();
	}

	private void list() {
		System.out.println("--------------------團隊成員列表---------------------");
		System.out.println("TID/ID\t姓名\t年齡\t工資\t職位\t獎金\t股票");
		Programmer[] allMembers = ts.getAllMembers();
		for (int i = 0; i < allMembers.length; i++) {
//			System.out.println(allMembers[i]);//自動呼叫toString()
			System.out.println(allMembers[i].getMemberInfo());
		}
		System.out.println("-----------------------------------------------------");
	}

	private void getAllEmployee(){
		System.out.println("ID\t姓名\t年齡\t工資\t職位\t狀態\t獎金\t股票\t領用裝置");
		//(1)獲取所有的員工的資訊
		
		Employee[] all = ns.getAll();
		
		//(2)遍歷
		for (int i = 0; i < all.length; i++) {
			System.out.println(all[i]);//自動呼叫toString()
		}
	}
}

6.main函式

package com.atguigu.test;
import com.atguigu.view.TeamView;

public class TeamTest {
	public static void main(String[] args) {
		TeamView t = new TeamView();
		t.menu();
	}
}

在這裡插入圖片描述

7.工具

package com.atguigu.utils;

public class Data {
    public static final int EMPLOYEE = 10;
    public static final int PROGRAMMER = 11;
    public static final int DESIGNER = 12;
    public static final int ARCHITECT = 13;

    public static final int PC = 21;
    public static final int NOTEBOOK = 22;
    public static final int PRINTER = 23;

    //Employee  :  10, id, name, age, salary
    //Programmer:  11, id, name, age, salary
    //Designer  :  12, id, name, age, salary, bonus
    //Architect :  13, id, name, age, salary, bonus, stock
    public static final String[][] EMPLOYEES = {
        {"10", "1", "段譽", "22", "3000"},
        {"13", "2", "令狐沖", "32", "18000", "15000", "2000"},
        {"11", "3", "任我行", "23", "7000"},
        {"11", "4", "張三丰", "24", "7300"},
        {"12", "5", "周芷若", "28", "10000", "5000"},
        {"11", "6", "趙敏", "22", "6800"},
        {"12", "7", "張無忌", "29", "10800","5200"},
        {"13", "8", "韋小寶", "30", "19800", "15000", "2500"},
        {"12", "9", "楊過", "26", "9800", "5500"},
        {"11", "10", "小龍女", "21", "6600"},
        {"11", "11", "郭靖", "25", "7100"},
        {"12", "12", "黃蓉", "27", "9600", "4800"}
    };

    //PC      :21, model, display
    //NoteBook:22, model, price
    //Printer :23, type, name
    public static final String[][] EQIPMENTS = {
        {},
        {"22", "聯想Y5", "6000"},
        {"21", "巨集碁 ", "AT7-N52"},
        {"21", "戴爾", "3800-R33"},
        {"23", "鐳射", "佳能 2900"},
        {"21", "華碩", "K30BD-21寸"},
        {"21", "海爾", "18-511X 19"},
        {"23", "針式", "愛普生20K"},
        {"22", "惠普m6", "5800"},
        {"21", "聯想", "ThinkCentre"},
        {"21", "華碩","KBD-A54M5 "},
        {"22", "惠普m6", "5800"}
    };
}
package com.atguigu.utils;
import java.util.*;

public class TSUtility {
    private static Scanner scanner = new Scanner(System.in);
	public static char readMenuSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false);
            c = str.charAt(0);
            if (c != '1' && c != '2' &&
                c != '3' && c != '4') {
                System.out.print("選擇錯誤,請重新輸入:");
            } else break;
        }
        return c;
    }

    public static void readReturn() {
        System.out.print("按Enter鍵繼續...");
        readKeyBoard(100, true);
    }

    public static int readInt() {
        int n;
        for (; ; ) {
            String str = readKeyBoard(2, false);
            try {
                n = Integer.parseInt(str);
                break;
            } catch (NumberFormatException e) {
                System.out.print("數字輸入錯誤,請重新輸入:");
            }
        }
        return n;
    }

    public static char readConfirmSelection() {
        char c;
        for (; ; ) {
            String str = readKeyBoard(1, false).toUpperCase();
            c = str.charAt(0);
            if (c == 'Y' || c == 'N') {
                break;
            } else {
                System.out.print("選擇錯誤,請重新輸入:");
            }
        }
        return c;
    }

    private static String readKeyBoard(int limit, boolean blankReturn) {
        String line = "";

        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            if (line.length() == 0) {
                if (blankReturn) return line;
                else continue;
            }

            if (line.length() < 1 || line.length() > limit) {
                System.out.print("輸入長度(不大於" + limit + ")錯誤,請重新輸入:");
                continue;
            }
            break;
        }
        return line;
    }
}

相關文章