0

我正在尝试制作一个简单的程序,用户尝试猜测 1 到 25 之间的数字,直到他们猜对了。我正在尝试将输入作为整数接收,以便我可以使用大于和小于符号。当我使用我在这个论坛的另一个答案中找到的命令时,它说有一个错误。我究竟做错了什么?

        int score = 0;
        int add = 1;

        while (add == 1)
        {
            Console.WriteLine("Guess A Number Between 1 and 25");
            string input = int.Parse(Console.ReadLine());
            score += add;

            if (input == 18)
            {
                Console.WriteLine("You Did It!");
                Console.WriteLine("Your Score was " + score);
                break;
            }
            else if (input > 25)
            {
                Console.WriteLine("Error.");
            }
            else
            {
                Console.WriteLine("Try Again. Score: " + score);
            }
        }
4

1 回答 1

0

将来自 ReadLine() 的响应存储为字符串,然后使用int.TryParse()尝试将该字符串转换为整数。编写下面的代码是为了向您展示使用if else块可能出现的所有可能状态。我还使用 abool来指示游戏何时结束,而不是使用break语句:

static void Main(string[] args)
{
    int number;
    string input;
    bool guessed = false;
    int score = 0;
    
    while (!guessed)
    {
        Console.Write("Guess A Number Between 1 and 25: ");
        input = Console.ReadLine();                
        if (int.TryParse(input, out number))
        {
            if(number>=1 && number<=25)
            {
                score++;
                if (number == 18)
                {
                    guessed = true;
                    Console.WriteLine("You Did It!");
                    Console.WriteLine("Your Score was " + score);
                }
                else
                {
                    Console.WriteLine("Try Again. Score: " + score);
                }
            }
            else
            {
                Console.WriteLine("Number must be between 1 and 25!");
            }
        }
        else
        {
            Console.WriteLine("That's not a number!");
        }
        Console.WriteLine();
    }
    Console.Write("Press Enter to Quit.");
    Console.ReadLine();
}
于 2020-06-28T04:25:50.830 回答