簡體   English   中英

在Java中從命令行讀取用戶輸入的正確方法

[英]proper way to read user input from command line in java

我希望能從最佳實踐中獲得一些意見,並從命令行中讀取用戶輸入的方式獲得意見。 有沒有建議的方法來執行此操作,我是否正確使用了try / catch塊?

我的示例在這里工作正常,但仍然想聽聽是否有一種“更清潔”的方法。 非常感謝。 例如,他是否需要在每個catch塊中返回語句? 或者,我應該將我的邏輯(條件)放在try塊中嗎?

公共類客戶{

public static void main(String[] args) {
    begin();
}

private static void begin(){
    Machine aMachine = new Machine();
    String select=null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while(aMachine.stillRunning()){
        try {
            select = br.readLine();
        } catch (IOException ioe) {
            System.out.println("IO error trying to read your selection");
            return;
        }catch(Exception ex){
            System.out.println("Error trying to evaluate your input");
            return;
        }

        if (Pattern.matches("[rqRQ1-6]", select)) {
            aMachine.getCommand(select.toUpperCase()).execute(aMachine);
        }
        /*
         * Ignore blank input lines and simply
         * redisplay options
         */
        else if(select.trim().isEmpty()){
            aMachine.getStatus();
        }
        else {                
            System.out.println(aMachine.badCommand()+select);
            aMachine.getStatus();
        }
    }
}

}

通常,我傾向於使用Scanner類從輸入行讀取。 使用掃描器類,您可以請求特定的類型(雙精度,整數,...,字符串)。 這也將為您進行驗證測試。

我不建議您以這種方式編寫輸入解析。 捕獲一個通用的異常會從MemoryError等中捕獲任何東西。堅持使用特定的異常並從那里處理它們。 如果輸入與預期的類型不匹配,則掃描程序將通過InvalidInputException(或可能會影響到的結果)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM