为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 128 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信