我有一个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);
2条答案
按热度按时间dffbzjpn1#
为什么不能声明为空
char
回答你的问题在你的代码中做一些小的改动,以便更好地工作
char
字面意义的使用before while循环。
然后用预期输入检查条件,如:
hc2pp10m2#
您可以使用do while循环来执行此操作