I am trying to run the code below on .Net fiddle, and am encountering the following problem. The randomly generated target number seems to change and the hints (higher or lower) seem to change with your guesses. Why is this happening?

I'm also sure that the code could use some optimizations, I'm a beginner and using a chromebook at school to practice.

using System;

public class Program
{
    public static void Main()
    {
        var random = new Random();
        int i = random.Next(0, 101);
        int tries = 5;
        Console.WriteLine("I'm thinking of a number between 1 and 100. Guess it in 5 tries.");
    Start:
        string feedback = Console.ReadLine();
        int guess = Convert.ToInt32(feedback);
        
        if (guess == i)
        {
            Console.WriteLine("You won with " + tries + " tries left!");
        }
        else if (guess > i && tries > 1)
        {
            tries--;
            Console.WriteLine("Try lower. " + tries + " tries left.");
            goto Start;
        }
        else if (guess < i && tries > 1)
        {
            tries--;
            Console.WriteLine("Try higher. " + tries + " tries left.");
            goto Start;
        }
        else
        {
            Console.WriteLine("Sorry, you ran out of tries. The nubmer was " + i + ".");
        }       
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

.Net fiddle is not suitable for this because you don't have a continuous session to a single instance of the app

Consider it works something like:

  • fiddle runs the app, including all output, until it needs your input
  • fiddle kills the app and collects your input
  • fiddle runs the app again, provides the input you provided, shows you the new output and kills it again, asking you for new input
  • fiddle runs the app again providing both the inputs it has seen you provide, and kills the app again...

It works for programs that have a deterministic behavior for a set of inputs but not where the some vital thing the program does is pick a random number.

To test this code, don't use random, just use a constant. If the logic works for a randomly generated number (and the generation logic is sound) it'll work for a constant too

If you really do want some element of guessing try this:

Console.WriteLine("Enter a word");
var word = Console.ReadLine();
var i = Math.Abs(word.GetHashCode())%101;

It will prompt you for a word and make a number out of it but it's not easily predictable what word will become what number so it maintains an element of guessing. Because the number is derived from your input it's compatible with this "recycle providing all the previous inputs" behavior

Now, about that goto..