我使用了一些代码,然后在循环中再次使用它。它看起来很难看,有没有办法改善它?

时间:2015-05-25 21:34:09

标签: c#

我开始学习c#。我写了一个简单的猜数字程序。它工作,但我在循环之前使用一些代码然后我在循环中重用它。肯定有更好的办法。

using System;

namespace Guessthenumber
{
class Program
{
    static void Main()
    {
        Random rnd = new Random();
        string guess;
        int yourguess;
        int dice = rnd.Next(1, 7);
        Console.WriteLine("Guess a number between 1 and 6");
        guess = Console.ReadLine();
        yourguess = int.Parse(guess);

这是我在循环中再次重复的模式。有没有办法避免这种情况?

        if (yourguess > dice)
        {
            Console.WriteLine("Lower");
        }
        if (yourguess < dice)
        {
            Console.WriteLine("Higher");
        }
        if (yourguess == dice)
        {
            Console.WriteLine("Correct!");
        }
        while (yourguess != dice)
        {


          guess = Console.ReadLine();
          yourguess = int.Parse(guess);
            if (yourguess > dice)
            {
                Console.WriteLine("Lower");
            }
            if (yourguess < dice)
            {
                Console.WriteLine("Higher");
            }
            if (yourguess == dice)
            {
                Console.WriteLine("Correct!");
            }

        }
        Console.WriteLine("Press enter to exit");
        Console.ReadLine();
    }
}
}

2 个答案:

答案 0 :(得分:3)

使用do, while循环代替while。这样,代码变为:

static void Main()
{
    Random rnd = new Random();
    string guess;
    int yourguess;
    int dice = rnd.Next(1, 7);
    Console.WriteLine("Guess a number between 1 and 6");
    do
    {
        guess = Console.ReadLine();
        yourguess = int.Parse(guess);

        if (yourguess > dice)
        {
            Console.WriteLine("Lower");
        }
        if (yourguess < dice)
        {
            Console.WriteLine("Higher");
        }
        if (yourguess == dice)
        {
            Console.WriteLine("Correct!");
        }
    } while (yourguess != dice);

    Console.WriteLine("Press enter to exit");
    Console.ReadLine();
}

答案 1 :(得分:2)

是的,请改用do-while loop

do
{
    // Repeated stuff
} while (yourguess != dice);