[英]Loop either not working or never ending c#
我正在尝试学习循环,但它们正处于破坏我的边缘。 这个循环要么根本不起作用,要么永远不会结束,这导致了一些严重的压力。 如果有人可以帮助我,那就太好了。 计划是让循环继续,直到有人写出是/是/是(最好是任何形式的是),然后中断并继续代码的下一部分,即一些读行和写行,还没有走那么远,因为循环还没有让我。 非常感谢您的任何意见。
Console.WriteLine("Hello Inspector!");
Console.WriteLine("Are you ready to identify the suspects? Just write yes and we'll get started.");
string Start = Console.ReadLine();
Startup();
while (Start.Contains("")==false)
{
Console.WriteLine("Just type yes when you are ready.");
if (Start.Contains("Yes") == true)
Console.WriteLine("Let's start.");
break;
}
}
static void Startup()
{
string Start = Console.ReadLine();
if (Start.Contains("yes") == true)
{
Console.Clear();
Console.WriteLine("Here are the suspects:");
}
else
{
Console.WriteLine("Just type yes when you are ready.");
}
}
}
}
您的代码有几个问题:
1)你只读过一次用户输入 - 正如m.sh已经指出的,你需要把
Start = Console.ReadLine();
在你的while
循环中。
2)如果您的条件得到满足,您只希望捕获的break
不在范围内,因为您缺少这样的封闭{ }
:
if (Start.Contains("Yes") == true)
{
Console.WriteLine("Let's start.");
break;
}
3) 不是直接的编程错误,而是广泛反对:明确比较布尔值。 只需使用
if (Start.Contains("yes"))
代替
if (Start.Contains("yes") == true)
4) 也已经提到 - 使用.ToLower()
允许任何输入大小写
if (Start.ToLower().Contains("yes"))
将适用于yes
, YES
, yEs
, YeS
, ...
将部件放在一起以形成工作循环
// many coding guidelines ask you to use string.Empty rather than "". [I.]
string Start = string.Empty;
while (!Start.ToLower().Contains("yes"))
{
Console.WriteLine("Just type yes when you are ready.");
Start = Console.ReadLine();
}
Console.WriteLine("Let's start.");
注意否定!
对于while
条件 - 只要不满足条件,这就会使您的循环运行,而不必在需要中断时检查循环内部。
另一种循环方式是do { } while();
在循环结束时检查您的条件:
string Start = string.Empty;
do
{
Console.WriteLine("Just type yes when you are ready.");
Start = Console.ReadLine();
}
while (!Start.ToLower().Contains("yes"));
如果您单步调试在调试器中运行的代码,您会注意到不同的行为以及如何do {} while()
视为比while() { }
更快的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.