[英]C# Do-While statement to validate user input
我想創建一個簡單的do-while語句,以確保用戶輸入的內容是Y或N,如果沒有,請他們再次輸入。 如果是Y或N,則應用繼續。 到目前為止,這是我所擁有的,但是我的應用程序雖然陷入了一個循環,要求用戶輸入。 C#的新手-感謝您的幫助。
string answer = "";
do
{
//Ask the user if they want to roll the dice
Console.WriteLine("Would you like to roll the dice (y or n)?");
//Get the user's response and validate that it is either 'y' or 'n'.
answer = Console.ReadLine();
} while (answer != "Y" || answer != "N");
看起來像一個簡單的布爾邏輯錯誤。
您的while語句應為:while(answer!=“ Y” && answer!=“ N”);
因為您要確保答案不是Y,答案也不是N。因此,請循環兩次。 希望這可以幫助!
您的邏輯是OR ||
代替AND &&
。 它總是不是Y
或不是N
因為它不能一次都為。 當它為N
時不是Y
,反之亦然。
使用AND &&
代替。
另外,您的比較區分大小寫。 考慮檢查大小寫。
更改|| 到&&,這應該可以為您解決。
另一種查看方式可能是:
中斷條件是答案為“ Y”或答案為“ N”。
您希望在不滿足中斷條件時繼續循環,這樣您就可以
(answer ==“ Y” || answer ==“ N”),然后不是結果
while(!(answer == "Y" || answer == "N")
2件事
||
與&&
Y
& N
匹配,導致用戶可以輸入y
。 Y
和y
都是用戶的積極決定。 answer.ToUpper() != "Y" && answer.ToUpper() != "N"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.