c#中的循环问题

本文关键字:问题 循环 | 更新日期: 2023-09-27 18:11:00

我似乎有一个问题,我需要一个整数从循环的循环条件,这里的代码:

do {
    Console.WriteLine();
    Console.WriteLine("What file would you like to test?");
    Console.WriteLine("1. Royal Flush");
    Console.WriteLine("2. Straight Flush");
    Console.WriteLine("3. Four of a Kind");
    Console.WriteLine("4. Full House");
    Console.WriteLine("5. Flush");
    Console.WriteLine("6. Straight");
    Console.WriteLine("7. Three of a Kind");
    Console.WriteLine("8. Two Pair");
    Console.WriteLine("9. Pair");
    Console.WriteLine("10. Exit");
    choiceInt = Convert.ToInt32(Console.ReadLine());
} while (choiceInt < 10 || choiceInt > 0);

我需要choiceInt作为循环的条件,为了让它工作我必须让它循环一次才能得到一个值,

c#中的循环问题

您的><是错误的:当选择错误时,您想要一个评估true的条件(因此循环应该继续要求用户输入)。由于do/while在条件变为false时退出,因此可以确定退出循环后choiceInt在有效范围内。

条件应该是这样的:

do {
    ...
} (choiceInt < 0 || choiceInt > 10);
//    ^^^^              ^^^^
//  negative          above ten

这将为您工作:

    static void Main(string[] args)
    {
        string consoleInput;
        ShowOptions();         
        do
        {
            consoleInput = Console.ReadLine();
            if (consoleInput == "10")
                Environment.Exit(0);
            DoSomething();
            ShowOptions();
        } while (consoleInput != null && consoleInput != "10");
    }
    private static void ShowOptions()
    {
        Console.WriteLine();
        Console.WriteLine("What file would you like to test?");
        Console.WriteLine("1. Royal Flush");
        Console.WriteLine("2. Straight Flush");
        Console.WriteLine("3. Four of a Kind");
        Console.WriteLine("4. Full House");
        Console.WriteLine("5. Flush");
        Console.WriteLine("6. Straight");
        Console.WriteLine("7. Three of a Kind");
        Console.WriteLine("8. Two Pair");
        Console.WriteLine("9. Pair");
        Console.WriteLine("10. Exit");
    }
    private static void DoSomething() { Console.WriteLine("I am doing something!"); }

我倾向于尝试整理代码,使其更通用。试试这样做:

var options = new []
{
    new { option = 1, text = "Royal Flush" },
    new { option = 2, text = "Straight Flush" },
    new { option = 3, text = "Four of a Kind" },
    new { option = 4, text = "Full House" },
    new { option = 5, text = "Flush" },
    new { option = 6, text = "Straight" },
    new { option = 7, text = "Three of a Kind" },
    new { option = 8, text = "Two Pair" },
    new { option = 9, text = "Pair" },
    new { option = 10, text = "Exit" },
};
string choice;
do
{
    Console.WriteLine();
    Console.WriteLine("What file would you like to test?");
    Console.WriteLine(
        String.Join(
            Environment.NewLine,
            options.Select(o => String.Format("{0}. {1}", o.option, o.text))));
    choice = Console.ReadLine();
} while (options.Take(9).Any(o => o.option.ToString() == choice));