2017-08-10 80 views
1

我有一个方法可以检查用户是否是学生,但我无法验证条件。验证输入的char变量。 Do-while循环不会中断

char custStud = '0'; 
Scanner input = new Scanner(System.in); 

do{ 
     System.out.println("Are you a student? (Type Y or N): "); 
     custStud = input.next().charAt(0); 
     custStud = Character.toLowerCase(custStud); 
    } 
    while (custStud != 'y' || custStud != 'n'); 

当我启动此程序时,即使输入'y'或'n',它也不会中断循环。我怀疑custStud在更改为小写字母时可能意外更改了类型,但我不确定。 如何让这个循环正常工作?

+2

'而(custStud =' y'|| custStud!='n');'永远是真的 –

+0

@batPerson如果N被按下会发生什么,循环继续如果用户输入N –

+0

@batPerson如果有帮助 –

回答

4

while (custStud != 'y' || custStud != 'n')总是如此,因为custStud不能等于'y'和'n'。

您应该更改条件:

while (custStud != 'y' && custStud != 'n') 
+0

唉!当然!非常感谢你! – batPerson

1

您在这里错了:

while (custStud != 'y' || custStud != 'n');// wrong 
while (custStud != 'y' && custStud != 'n');// correct 

尝试运行这段代码:

 char custStud = '0'; 
     Scanner input = new Scanner(System.in); 

     do{ 
      System.out.println("Are you a student? (Type Y or N): "); 
      custStud = input.next().charAt(0); 
      custStud = Character.toLowerCase(custStud); 
     } 
     while (custStud != 'y' && custStud != 'n'); 
     System.out.print("\n answer:"+custStud);