Problem with DotNetFiddle and Console.ReadLine that causes a Re-run when pressing ENTER key

1.3k Views Asked by At

I have a weird scenario using a C# online compiler with this code:

int randomNumber;
int guess;
int countGuess;
bool correctGuess = false;
bool alreadyCalled = false;
int lastGuess;

public void Main()
{
    if(!alreadyCalled)
    {
        RandomNumberGenerator();
        alreadyCalled = true;
    }
    GuessWhatNumber();
}

private void GuessWhatNumber()
{
    while(!correctGuess)
    {
        Console.WriteLine("Guess the number : ");
        guess = Convert.ToInt32(Console.ReadLine());
        
        if(guess > randomNumber)
        {
            Console.WriteLine("Too High");
            correctGuess = false;
        }
        else if(guess < randomNumber)
        {
            Console.WriteLine("Too Small");
            correctGuess = false;
        }
        else    
        {
            Console.WriteLine("Correct!");
            correctGuess = true;
            countGuess = 0;
            Environment.Exit(0);
        }
        
        if(lastGuess != guess)
        {
            countGuess+=1;
            Console.WriteLine("Count of Guess : " + countGuess);
        }
        else
        {
            Console.WriteLine("Count of Guess is Still: " + countGuess);
        }
        lastGuess = guess;
    }
}

private void RandomNumberGenerator()
{
    Random rand = new Random();
    randomNumber = rand.Next(50);
    Console.WriteLine("Number To Guess : " + randomNumber); 
}

The Random Number Generator method must be called only once but on that online compiler it keeps calling and calling the method all over again. What am I doing wrong here? Or is it the compiler?

Dotnetfiddle.net settings are:

  • C#
  • Console
  • Compiler: .NET 4.7.2
  • No nugets packages
  • Autorun: NO
1

There are 1 best solutions below

3
On

Once you run the code it is send to the server as request and it'll return the results as text to display in the interface. Once it encounters a point where it requires the users input instead of waiting for the input the full request is send again, but this time with the information from the input window. Then on the backend the full request runs again and automatically adds the input from the users as far as it's known.

In most cases that would be no problem because the same script usually yields the same results. This is a different case however because you added a random element into the script. So each time you input new data everything that happened before runs again and may yield different results.