亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

y/n 輸入驗證,包括無輸入 Enter 鍵

y/n 輸入驗證,包括無輸入 Enter 鍵

慕標琳琳 2021-09-03 15:38:51
我試圖在一種方法中捕獲沒有輸入(輸入鍵)和無效輸入除 y/n 之外的所有內容。我嘗試了兩種不同的方式(粘貼),但我無法同時使用“輸入鍵”和“錯誤輸入 y/n”。感謝您的幫助。第一次嘗試:public static String askToContinue(Scanner sc) {String choice = "";boolean isValid = false;while (!isValid){System.out.print("Continue? (y/n): ");    if (sc.hasNext()){        choice = sc.next();        isValid = true;    } else {System.out.println("Error! "                + "This entry is required. Try again");        }    if (isValid && !choice.equals("y") || !choice.equals("n")) {        System.out.println("Error! Entry must be 'y' or 'n'. Try again");        isValid = false;    }   }    //sc.nextLine();  // discard any other data entered on the line    System.out.println();    return choice;   }           2nd attempt    public static String askToContinue(Scanner sc) {    System.out.print("Continue? (y/n): ");    String choice;    while (true) {choice = sc.next();    //?????????????????????????????????????????????????????        if (choice.length() == 0){ System.out.println("Error! "                + "This entry is required. Try again");            continue;        }        if (!(choice.equals("y") || choice.equals("n"))) {            System.out.println("Error! Entry must be 'y' or 'n'. Try                   again");            continue;        }        break;        }    sc.nextLine();  // discard any other data entered on the line    System.out.println();    return choice;    }
查看完整描述

2 回答

?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

我嘗試了您的代碼的第一次嘗試。我用注釋行進行了解釋,注釋行包含在下面的代碼中,例如;


public static String askToContinue(Scanner sc) {

    String choice = "";

    boolean isValid = false;

    while (!isValid) {

        System.out.print("Continue? (y/n): ");

        choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input

        isValid = true;

        if (choice.isEmpty()) {  //this isEmpty for empty enter

            System.out.println("Error! "

                    + "This entry is required. Try again");

        }

        System.out.println(choice);

        //this logic if not y or n , it will return error

        if (!choice.equals("y") && !choice.equals("n")) {

            System.out.println("Error! Entry must be 'y' or 'n'. Try again");

            isValid = false;

        }

    }

    //sc.nextLine();  // discard any other data entered on the line

    System.out.println();

    return choice;

}


查看完整回答
反對 回復 2021-09-03
?
繁星淼淼

TA貢獻1775條經驗 獲得超11個贊

您在第一種情況下的 if 語句是錯誤的。您正在檢查是否選擇is not equal to 'y'  not equal to 'n'將始終為真。

改變

if (isValid && !choice.equals("y") || !choice.equals("n"))

if (isValid && !choice.equals("y") && !choice.equals("n"))


查看完整回答
反對 回復 2021-09-03
  • 2 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號