mercredi 13 janvier 2021

How to use an if statement that accounts for an int in a singular sense

I'm new to coding and C# so apologies for the generic question. I've created a basic random number guessing game, and when I try to put if statements around the correct answers it appears to fail. If the guess is correct on the first go I want the statement to say congrats it took you 1 try, and if the guess is correct on the third go I want the statement to say congrats it took you 3 tries.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            Random rand = new Random();
            int guess = 0;
            string welcome = "Guess a number between 1 and 10";
            int num = rand.Next(1, 10);
            int guessCount = 0;
            int guessLimit = 3;
            bool outOfGuesses = false;
            Console.WriteLine(welcome);


            int i = 0;

            while (guess != num && guessCount < guessLimit)
                
            {
                try
                {
                    guess = Convert.ToInt32(Console.ReadLine());

                    if (guess > num)
                    {
                        Console.WriteLine("Too High");
                        guessCount++;
                    }
                    if (guess < num)
                    {
                        Console.WriteLine("Too Low");
                        guessCount++;
                    }
                }

                catch
                {
                    Console.WriteLine("Guess must be a number");
                    i--;
                }


                i++;
            }
            if (guess == num && guessCount != 1)
            {
                Console.WriteLine("Congrats, it took you " + i + " tries");
            }
            if (guess == num && guessCount == 1)
            {
                Console.WriteLine("Congrats, it took you " + i + " try");
            }
            if (guess != num && !outOfGuesses)
            {
                Console.WriteLine("GAME OVER, you have lost");
            }
            Console.ReadLine();
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire