0

I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?

        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);
            }
        }
Guru Stron
  • 102,774
  • 10
  • 95
  • 132

1 Answers1

0

Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:

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();
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40