/** * 工具類的作用 * 處理各種情況下用戶的輸入,并且能夠按照程式員的要求,得到用戶的控制臺輸入, */ public class Utility { //靜態屬性 private static Scanner scanner = new Scanner(System.in); /** * 功能:讀取鍵盤輸入的一個選單選項,值:1-5的范圍 * * @return 1-5 */ public static char readMenuSelection() { char c; while (true) { String str = readKeyBoard(1, false); c = str.charAt(0);//將字串轉換為字符char if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5') { System.out.println("選擇錯誤,請重新輸入!"); } else break; } return c; } /** * 功能:讀取鍵盤輸入的一個字符,如果直接按回車,則回傳指定的默認值 * * @param defaultValue 指定的默認字串 * @return 默認值或輸入的字符 */ public static char readChar(char defaultValue) { String str = readKeyBoard(1, true);//要么是空串,要么是輸入的字串 return (str.length() == 0 ? defaultValue : str.charAt(0)); } public static char readChar() { String str = readKeyBoard(1, false);//要么是空串,要么是輸入的字串 return str.charAt(0); } /** * 功能:讀取鍵盤輸入的整型,長度小于2位 * * @parameter 整數 */ public static int readInt(int defaultValue) { int n; while (true) { String str = readKeyBoard(10, true); if (str.equals("")) { return defaultValue; } //例外處理 try { n = Integer.parseInt(str); break; } catch (NumberFormatException e) { System.out.println(e); } } return n; } /** * 功能:讀取鍵盤輸入的指定長度的字串 * * @return 指定長度的字串 * @parameter limit 限制的長度 */ 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; while (true) {//無限回圈 //在這里,將接受到字符,轉成了大寫字母 //y=>Y n=>N String str = readKeyBoard(1, false).toUpperCase(); c = str.charAt(0); if (c == 'Y' || c == 'N') { break; } else { System.out.println("選擇錯誤,請重新輸入:"); } } return c; } /** * 功能:從鍵盤讀取字串 * * @param flag 判斷是否嚴格 * @param limit 是否可以為空字串 * @return str 符合要求的字串 */ public static String readKeyBoard(int limit, boolean flag) { String str; do { str = scanner.nextLine(); if (str.length() == 0) { if (flag == false) { while (true) { System.out.println("請輸入:"); str = scanner.nextLine(); if (str.length() != 0) { break; } } } else return ""; } if (str.length() > limit){ System.out.print("請輸入長度不大于" + limit +"的字串:"); } }while (str.length() > limit); return str; } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544261.html
標籤:其他
上一篇:3. 投票 案例專案(合集)
下一篇:python定時器
