2017-09-29 46 views
0

所以我想驗證用戶是否鍵入是或否,並繼續詢問,直到他們鍵入一個或另一個。這是我的代碼到目前爲止。試圖驗證用戶是否鍵入是或否

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");   
String input2 = scan.nextLine(); 
boolean d = input2.equals("Yes"); 
System.out.println(d); 

while ((d != false) || (d != true)) { 
    System.out.println("Invalid Input. Please try again"); 
    input2 = scan.nextLine(); 
    d = input2.equals("Yes"); 
    System.out.println(d); 
} 

我哪裏錯了?我是新來的Java。任何幫助將不勝感激。

編輯:我寫的很糟糕。我要做的是這種邏輯。 詢問用戶他們是否想要鑽石而不是金字塔。 a。用戶必須輸入「是」或「否」。 b。如果用戶不鍵入這些內容,請再次詢問,直到他們提供適當的輸入。

+2

我在移除Javascript標籤; Java和Javascript是不相關的語言。在你的問題中包括什麼問題也是很好的 - 症狀就像它一樣。你描述了你想要的,並且你給了一些代碼,但是你沒有真正地說出問題所在。這就是說,試着弄清楚'd!= false || d!= true'對每個'd'的兩個可能值進行評估。 – yshavit

+0

聽起來像我的一個prodject領導我:)。 「你能做到嗎?」,我:「不」,他:「輸入無效,請重試」 – patrik

回答

2

您結束了在

while ((d != false) || (d != true)) 

具有的無限循環,因爲d是一個boolean即使更新要麼是truefalse並且在這兩種情況下將滿足上述條件。相反,你可以把它改成

System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");   
String input2 = scan.nextLine(); 
boolean d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); // confirms if the user input is Yes/No or invalid other than that 
.... 
while (!d) { // d==false ' invalid user input 
    System.out.println("Invalid Input. Please try again"); 
    input2 = scan.nextLine(); 
    d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); 
    System.out.println(d); 
    // also printing a boolean would print either true or false base on your input; you migt want to perform some other action 
} // this would exit on user input "Yes" 
0

布爾只能等同於真或假的所以你的while循環將執行不管是什麼,因爲d爲真,否則將是錯誤的。我想你只想做

while (d != true) 
0

您正在使用或符(||)在你的條件,只要用戶輸入你的條件之一是假的,另一種是真正的所以這就是爲什麼它不工作的罰款。 如果你想停止要求在真實值寫下面的條件。

while(d != true)