尚硅谷JavaSE進階第9章Java異常處理項目3:開發團隊調度系統五、把鍵盤輸入工具類TSUtility添加到項目中

5、把鍵盤輸入工具類TSUtility添加到項目中

直接將提供的TSUtility.java文件拷貝到com.atguigu.util包中,發現須要修改包名。java

第二發現出現亂碼,由於提供的文件是UTF-8格式的,若是你默認的項目字符編碼爲GBK的話,就會亂碼,解決辦法能夠用記事本打開TSUtility.java文件,把代碼複製到eclipse中。或者修改項目的字符編碼爲UTF-8,不過設置項目字符編碼最好在項目一開始。eclipse

package com.atguigu.util;工具

 

import java.util.*;大數據

 

public class TSUtility {ui

    private static Scanner scanner = new Scanner(System.in);編碼

 

public static char readMenuSelection() {spa

        char c;orm

        for (; ; ) {教程

            String str = readKeyBoard(1, false);ip

            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("按回車鍵繼續...");

        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;

    }

}

 本教程由尚硅谷教育大數據研究院出品,如需轉載請註明來源,歡迎你們關注尚硅谷公衆號(atguigu)瞭解更多。

相關文章
相關標籤/搜索