我尝试使用循环从用户那里获得正确的所需输入。循环不会停止。我头脑风暴了一段时间,但无法修补虫子。
char choice;
System.out.println("Below is a auto generated description for your property.Is it okay for you? (y/n)");
choice = sc.next().charAt(0);
for(;(choice!='y' || choice !='Y' || choice!='n' || choice !='N' );)
{
choice = sc.next().charAt(0);
System.out.println("Please enter 'y' or 'n'.");
}
// ... other codes ... //
请帮忙! 谢谢。
答案 0 :(得分:5)
choice != 'y' || choice != 'Y'
以上测试永远是真实的。如果选择是y,则choice != 'Y'
为真,因此整个条件也是如此。如果选择为Y,则choice != 'y'
为真,因此整个条件也是如此。
您希望&&
代替||
。
此外,for (; condition;)
在写为while (condition)
时更具可读性。
答案 1 :(得分:3)
for(; !(choice=='y' || choice =='Y' || choice=='n' || choice =='N' ) ;)
{
choice = sc.next().charAt(0);
System.out.println("Please enter 'y' or 'n'.");
}
只需添加!
即可。在我看来,while
循环在这里更合适。
while(user did not enter y or n){
// loop
}
答案 2 :(得分:0)
使用以下代码
你应该使用&&运算符在for或while循环中。
Scanner sc = new Scanner(System.in);
char choice;
System.out.println("Below is a auto generated description for your property.Is it okay for you? (y/n)");
choice = sc.next().charAt(0);
while(choice!='y' && choice !='Y' && choice!='n' && choice !='N' ){
System.out.println("Please enter 'y' or 'n'.");
choice = sc.next().charAt(0);
}