簡體   English   中英

C# - 使用 ReadKey 進行循環

[英]C# - Use ReadKey for loop

我一直在搜索 web 大約一個小時,但我找不到我的問題的答案。 我對編程很陌生,我希望我不會浪費你的時間。 如果單擊“Y”,我希望我的程序循環,如果單擊“N”則退出,如果單擊任何其他按鈕,則不執行任何操作。 干杯!

Console.Write("Do you wan't to search again? (Y/N)?");
if (Console.ReadKey() = "y")
{
    Console.Clear();
}
else if (Console.ReadKey() = "n")
{
    break;
} 

您在此處有Console.ReadKey方法的示例:

http://msdn.microsoft.com/en-us/library/471w8d85.aspx

//Get the key
var cki = Console.ReadKey();

if(cki.Key.ToString() == "y"){
    //do Something
}else{
    //do something
}

您會以這種方式丟失擊鍵。 存儲Readkey的返回值,以便將其拆分。
另外,C#中的比較是通過==完成的,而char常量使用單引號( ' )。

ConsoleKeyInfo keyInfo = Console.ReadKey();
char key = keyInfo.KeyChar;

if (key == 'y')
{
    Console.Clear();
}
else if (key == 'n')
{
   break;
}

您可以使用keychar來檢查是否按下了字符使用以下示例可以理解

Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
    Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
    Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X &&
    info.Modifiers == ConsoleModifiers.Control)
{
    Console.WriteLine("You pressed control X");
}

大概通過“什么都不做”,您打算要求用戶嘗試按下有效鍵,直到他們這樣做。 您可以使用do 語句(又名do loop )在某些條件為真時重復某些代碼,例如:

var validKey = false;
var searchAgain = false;

do
{
    Console.Write("Do you want to search again? (Y/N): ");
    string key = Console.ReadKey().KeyChar.ToString().ToLower(System.Globalization.CultureInfo.InvariantCulture);
    Console.WriteLine();

    if (key == "y")
    {
        validKey = true;
        searchAgain = true;
    }
    else if (key == "n")
    {
        validKey = true;
        searchAgain = false;
    }
    else
    {
        Console.WriteLine("Please press the 'Y' key or the 'N' key.");
    }

} while (!validKey);

// Now do something depending on the value of searchAgain.

我在!validKey中使用了“not”,因為這樣讀起來更好:do {this code} while(用戶沒有按下有效鍵)。 如果您認為使用該結構的代碼可讀性更好,您可能更喜歡使用while循環。

.ToLower(System.Globalization.CultureInfo.InvariantCulture)位使得按下“y”或“Y”無關緊要,它很有可能處理任何字母,即使是那些有意外的大寫/小寫變化; 請參閱土耳其語的國際化:帶點和不帶點的字母“I”和土耳其有什么問題? 解釋為什么小心這種事情是個好主意。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM