如何验证扫描仪是否收集到正确的字符,否则 运行 在 JAVA 中再次处理?

How to validate if a scanner collects the correct character, otherwise run process again in JAVA?

我有一个 Java 程序,我想询问用户是创建储蓄银行账户还是活期银行账户。

问题:“您想创建一个储蓄账户 (Y/N) 吗?”

// Collect Character to validate a savings or current account:
char yes_no = 'a'; //Why can't declare empty char?

System.out.println(ANSI_PURPLE + "Do you want to create a Savings Account (Y/N)?");
System.out.print(ANSI_RESET + " Choose an option > ");

//Check if input is valid. Otherwise allow user to select again:
while(!sc.hasNext()) {
   System.out.println(ANSI_RED + " ERROR: Invalid option! ");
   System.out.print(ANSI_RESET + " Choose an option > ");
   yes_no = sc.next().charAt(0);
}

if (yes_no == 'Y' || yes_no == 'y') {
    System.out.println("Y");
} else if(yes_no == 'N' || yes_no == 'n') {
    System.out.println("N");
} else {
    //run again to collect valid input
}

使用整数我可以做这样的事情:

// Check if input is valid. Otherwise allow user to select again:
while(!sc.hasNextInt()) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Choose an option > ");
    sc.next();
}
        
// Store input on variable and process request:
menuInput = sc.nextInt();
menuManager(menuInput);

为什么我不能对角色做类似的事情?


我的问题的正确答案:

// Collect Character to validate a savings or current account:
char yes_no = 'a';
System.out.println(ANSI_PURPLE + "Do you want to create a Savings Account (Y/N)?");
System.out.print(ANSI_RESET + " Choose an option > ");
yes_no = sc.next().charAt(0);

// Check if input is valid. Otherwise allow user to select again:
while (!(yes_no == 'Y' || yes_no == 'y' || yes_no == 'N' || yes_no == 'n')) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Choose an option > ");
    yes_no = sc.next().charAt(0);
}
System.out.println("input was " + yes_no);

您可以使用 do while 循环来做到这一点

        Scanner scanner = new Scanner(System.in);
        String answer = "";
        char ch;
        do{
            System.out.println("Enter Value");
            answer = scanner.nextLine();
            ch = answer.charAt(0);
            if(ch=='Y' || ch=='y' || ch=='N' || ch=='n'){
                break;
            }
        }while(true);
        System.out.println(ch);
  1. 为什么不能声明为空charAnswer for your question
  2. 对您的代码做一些小改动,以便与 char 文字
  3. 一起正常工作

在 while 循环之前使用。

System.out.println(ANSI_PURPLE + "Do you want to create a Savings Account (Y/N)?");
System.out.print(ANSI_RESET + " Choose an option > ");
yes_no = sc.next().charAt(0);

然后使用您预期的输入检查条件,例如:

while (!(yes_no == 'Y' || yes_no == 'y' || yes_no == 'N' || yes_no == 'n')) {
    System.out.println(ANSI_RED + " ERROR: Invalid option! ");
    System.out.print(ANSI_RESET + " Choose an option > ");
    yes_no = sc.next().charAt(0);
}