简化代码(适合初学者)

时间:2017-03-25 16:07:18

标签: c#

我正在学习C#的第一周。 我想应该有一些方法在下面的代码中使用1“While()”条件而不是2。有没有办法让我的代码更简单:

/* ask the user to guess a number.
        any number between 10 and 20 is the RIGHT choice, 
        any other number outside of that scope is WRONG. */
        int num;
        Console.WriteLine("[Q] Quit or make your choice");
        string answer = Console.ReadLine();
        if (answer == "Q" || answer == "q")
            Console.WriteLine();
        else
        {
            num = Convert.ToInt32(answer);
            while (num < 10)
            {
                Console.WriteLine("Wrong, try again");
                num = Convert.ToInt32(Console.ReadLine());
            }
            while (num > 20)
            {
                Console.WriteLine("Wrong, try again");
                num = Convert.ToInt32(Console.ReadLine());
            }

            Console.WriteLine("Your number is {0} and it's RIGHT", num);
            Console.ReadKey();
        }

1 个答案:

答案 0 :(得分:1)

您可以使用OR运算符组合这两个条件:

/* ask the user to guess a number.
   any number between 10 and 20 is the RIGHT choice, 
   any other number outside of that scope is WRONG. */

int num;
Console.WriteLine("[Q] Quit or make your choice");
string answer = Console.ReadLine();

if (answer == "Q" || answer == "q")
    Console.WriteLine();
else
{
    num = Convert.ToInt32(answer);
    while (num < 10 || num > 20)
    {
        Console.WriteLine("Wrong, try again");
        num = Convert.ToInt32(Console.ReadLine());
    }

    Console.WriteLine("Your number is {0} and it's RIGHT", num);
    Console.ReadKey();
}