簡體   English   中英

在C#控制台中按Enter鍵時出錯

[英]Error when pressing the Enter key, C# console

我的代碼要求用戶輸入一個字母(將string轉換為char ),但是當按Enter鍵作為輸入時,代碼將崩潰。

我沒有設置任何條件以向用戶發送錯誤消息,以不按輸入處的Enter鍵並僅輸入字母。

這是我正在努力的部分:

public static char GetLetter(string prompt)
{
    char result;

    Console.Write("\n\t" + prompt + ":  ");
    result = Convert.ToChar(Console.ReadLine());

    if(result == '!' || result == '@' || result == '#'  || result == '$' || result == '%'  )
    // we can keep going with all the unwanted characters and numbers 
    {
        Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
        result = GetLetter(prompt);
        return result;
    }

    return result;
}

輸入時會出現錯誤,因為您得到一個空字符串,因此無法將其轉換為char。

我會為您提供:

char result;
string input = Console.ReadLine();

if (char.TryParse(input, out result))
{
    //The input is a char - write your code here.
}

//The input is not a char.

您可以使用Console.ReadKey()函數讀取字符,如下所示:

public static char GetLetter(string prompt)
{
    char result;

    Console.Write("\n\t" + prompt + ":  ");
    result = Console.ReadKey().KeyChar;

    if (result == '!' || result == '@' || result == '#' || result == '$' || result == '%')
    // we can keep going with all the unwanted characters and numbers 
    {
        Console.WriteLine("\n\t NO MATCH ! \n\t ,please try again using letters only , ");
        result = GetLetter(prompt);
        return result;
    }

    return result;
}

Console.ReadLine()將返回string ,而不是char ,而應使用Console.Read 從MSDN檢查詳細信息

暫無
暫無

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

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