[英]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.