检查号码是否在范围内

本文关键字:范围内 是否 号码 检查 | 更新日期: 2023-09-27 18:03:04

我试图使用整数数组制作一款智谋游戏,其中我让用户猜测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();
    }

检查号码是否在范围内

下面是代码的简化版本:

    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)