C# While TryParse

早过忘川 提交于 2019-12-02 07:20:39

问题


char typeClient = ' ';
bool clientValide = false;
while (!clientValide)
{
     Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
     clientValide = char.TryParse(Console.ReadLine(), out typeClient);
     if (clientValide)
         typeClient = 'c';
}

I'd like to make it so it doesn't exit the while unless the char is 'g' or 'c' help ! :)


回答1:


string input;
do {
    Console.WriteLine("Entrez le type d'employé (c ou g):");
    input = Console.ReadLine();
} while (input != "c" && input != "g");

char typeClient = input[0];



回答2:


Is you use Console.ReadLine, the user has to press Enter after pressing c or g. Use ReadKey instead so that the response is instantaneous:

bool valid = false;
while (!valid)
{
    Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
    var key = Console.ReadKey();
    switch (char.ToLower(key.KeyChar))
    {
        case 'c':
            // your processing
            valid = true;
            break;
        case 'g':
            // your processing
            valid = true;
            break;
        default:
            Console.WriteLine("Invalid. Please try again.");
            break;
    }
}



回答3:


You're really close, I think something like this will work well for you:

char typeClient = ' ';
while (typeClient != 'c' && typeClient != 'g')
{
    Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
    var line = Console.ReadLine();
    if (!string.IsNullOrEmpty(line)) { typeClient = line[0]; }
    else { typeClient = ' '; }
}

basically it reads the input into the typeClient variable when the user enters something so the loop will continue until they enter g or c.




回答4:


You can use ConsoleKeyInfo with Console.ReadKey() :

    ConsoleKeyInfo keyInfo;
    do {
        Console.WriteLine("\nEntrez le type d'employé (c ou g) : ");
        keyInfo = Console.ReadKey();
    } while (keyInfo.Key != ConsoleKey.C && keyInfo.Key != ConsoleKey.G);

Et puis après vous ferez votre bloque IF comme bon vous semblera pour votre type de client ;)



来源:https://stackoverflow.com/questions/15465664/c-sharp-while-tryparse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!