NOOB试图结合时以及是否语句
我正在尝试学习C#,并想尝试从头开始制作一个简单的程序,要求用户在1-3之间输入一个数字,每个数字都会赢得彩票,写“退出”应该退出该程序。当一个数字回答时,应该提示用户再次回答,直到选择退出。无论我在尝试组合一个时循环时要做什么,如果语句我会遇到错误或仅仅不会停止的无限循环。可能是一些简单的语法误解..任何帮助都将不胜感激。
到目前为止,这是我的代码:
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()
}
}
}
}
I'm trying to learn C# and wanted to try making a simple program from scratch that asks the user to enter a number between 1-3, every number yields a lottery win and writing "exit" is supposed to exit the program. When one number is answered the user is supposed to be prompted to answer again until choosing to exit. No matter what I do when trying to combine a while loop and if statements I get errors or just infinite loops that won't stop. Probably some simple syntax misunderstanding.. Any help would be greatly appreciated.
This is my code so far:
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()
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该起作用
This should work
userInput
的值永远不会在循环中更新,这意味着每次循环运行时,该值都保持不变。解决方案是将提示和读数移至循环的开始。
The value of
userInput
is never updated in the loop, which means that each time the loop runs, the value stays the same.A solution is to move the prompt and the reading into the start of the loop.
为了增加Zayenz的回答,这是所有无限循环的关键。评估决定是否开始循环的情况始终是正确的。如果您再次遇到这个问题,则只需要查看代码即可确保将您从循环中脱颖而出的任何东西实际上会更改所需的任何条件,以使条件变得错误;
To add to Zayenz's answer, this is the key to all infinite loops; the circumstance evaluated that decides whether or not to begin the loop is always true. If you ever have this problem again, you just need to look at the code to make sure that whatever should break you out of the loop actually changes whatever criteria it needs to in order to make the condition false;