我正在嘗試學習 C#,并想嘗試從頭開始制作一個簡單的程式,要求用戶輸入 1-3 之間的數字,每個數字都會中獎,寫“exit”應該退出程式。當一個號碼被回答時,應該提示用戶再次回答,直到選擇退出。無論我在嘗試組合 while 回圈和 if 陳述句時做什么,我都會遇到錯誤或只是不會停止的無限回圈。可能是一些簡單的語法誤解。任何幫助將不勝感激。
到目前為止,這是我的代碼:
static void Main(string[] args)
{
string userInput = "";
Console.Write("Pick a number between 1-3, type 'exit' to stop the program: ");
userInput = Console.ReadLine();
while (userInput != "exit")
if (userInput == "1")
{
Console.WriteLine("You won a car");
}
else if (userInput == "2")
{
Console.WriteLine("You won a boat");
}
else if (userInput == "3")
{
Console.WriteLine("Sorry, no luck this time. Try again");
}
else if (userInput == "exit")
{
Console.WriteLine("Exiting...");
break
}
else
{
Console.WriteLine("The number has to be between 1-3, try again.");
}
Console.ReadLine()
}
}
}
}
uj5u.com熱心網友回復:
這應該作業
static void Main(string[] args)
{
string userInput = "";
Console.Write("Pick a number between 1-3, type 'exit' to stop the program: ");
userInput = Console.ReadLine();
while (userInput != "exit")
{
if (userInput == "1")
{
Console.WriteLine("You won a car");
}
else if (userInput == "2")
{
Console.WriteLine("You won a boat");
}
else if (userInput == "3")
{
Console.WriteLine("Sorry, no luck this time. Try again");
}
else if (userInput == "exit")
{
Console.WriteLine("Exiting...");
break
}
else
{
Console.WriteLine("The number has to be between 1-3, try again.");
}
userInput = Console.ReadLine()
}
}
}
uj5u.com熱心網友回復:
的值userInput永遠不會在回圈中更新,這意味著每次回圈運行時,該值都保持不變。
一個解決方案是將提示和讀數移到回圈的開頭。
uj5u.com熱心網友回復:
為了補充 Zayenz 的答案,這是所有無限回圈的關鍵;決定是否開始回圈的評估情況總是正確的。如果你再次遇到這個問題,你只需要查看代碼以確保任何應該讓你脫離回圈的東西實際上會改變它需要的任何標準,以使條件為假;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460385.html
