检查数字是否在范围内

时间:2015-07-17 02:00:59

标签: c#

我正在尝试使用一组int进行策划游戏,我让用户猜测数字序列介于4-10而不是颜色之间。我的GetAValidNumber假设向用户显示提示和 从用户处获得指定的最小/最大范围内的数字 参数。如果输入的数字超出最小值/最大值 范围,然后将显示错误消息并显示 重新提示用户输入该号码但由于某种原因它没有正确验证。

任何指导都将不胜感激

    public static int GetAValidNumber(string inputMessage)
    {
        // declare variables
        int validInteger;
        bool inputIsValid = false;
        int lowValue = 1;
        int highValue = 10;
        while (!int.TryParse(Console.ReadLine(), out validInteger))
        {
            Console.WriteLine("Invalid entery - try again.");
            Console.Write(inputMessage, lowValue, highValue);
            do
            {
                while (!int.TryParse(Console.ReadLine(), out validInteger))
                {
                    Console.WriteLine("Invalid entery - try again.");
                    Console.Write(inputMessage);
                }
                if (validInteger < lowValue || validInteger > highValue)
                {
                    Console.WriteLine("Your number is out of Range: ");
                }
                else
                {
                    inputIsValid = true;
                }

            } while (validInteger < lowValue || validInteger > highValue);
        }
        return validInteger;
    }

    // This method directs the play of the game
    public static void PlayGame()
    {
        int userNumbers;
        int userGuess;
        int difficulty;
        int randomNumbers;

        Console.WriteLine("How Many Numbers Would You Like To Use When Playing(4-10): ");
        userNumbers = GetAValidNumber(Console.ReadLine());

        Console.WriteLine("Choose a difficulty level (1 -3");
        difficulty = GetAValidNumber(Console.ReadLine());
        Console.WriteLine("A 5-digit number has been chosen. Each possible digit may be the number 1, 2, 3, or 4");
        Console.ReadLine();
        Console.WriteLine("Enter Your Guess {0} guesses remaning", GetGameDifficulty(difficulty, randomNumbers = GetRandomNumberCount(difficulty)));
        userGuess = GetAValidNumber(Console.ReadLine());
        Console.WriteLine("Your Guess was {0}, Your Results are {1}", userGuess, CountHits(userGuess, randomNumbers));
        Console.ReadLine();

    }

1 个答案:

答案 0 :(得分:2)

以下是您的代码的简化版本:

    public static int GetAValidNumber(string inputMessage)
    {
        int validInteger = 0;

        //Range between 4 to 10
        int lowValue = 4; 
        int highValue = 10;

        int.TryParse(inputMessage, out validInteger);

        while (validInteger < lowValue || validInteger > highValue)
        {
            Console.WriteLine("Invalid entery - try again.");
            inputMessage = Console.ReadLine();
            int.TryParse(inputMessage, out validInteger);
        }
        return validInteger;

    }

这里的问题是您有多个while循环没有正确验证您的输入。

请注意,在您的其他验证号码输入上,您需要不同的范围,因此我建议您将lowValuehighValue设置为您的功能的额外参数:

public static int GetAValidNumber(string inputMessage, int lowValue, int highValue)