如何验证扫描器是否收集了正确的字符,否则在java中再次运行进程?

uelo1irk  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(268)

我有一个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);
dffbzjpn

dffbzjpn1#

为什么不能声明为空 char 回答你的问题
在你的代码中做一些小的改动,以便更好地工作 char 字面意义的
使用before 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);
}
hc2pp10m

hc2pp10m2#

您可以使用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);

相关问题