2017-08-10 81 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);