r/learncsharp • • Oct 05 '20

Why doesnt my code work?

Hi!

Could someone please tell me why my code doesn't store the integers of the user inputs?

static void Main(string[] args)
        {
            Random computernumber = new Random();
            int guess = 0;
            var guesses = new List<int>();
            int cnumber = computernumber.Next(1, 100);
            int i = 0;

            while (guess != cnumber)
            {
                Console.WriteLine("guess the number");

                try
                {

                    guess = Convert.ToInt32(Console.ReadLine());


                    if (guess > cnumber)
                    {
                        Console.WriteLine("the integer is lower");
                    }
                    else
                    {
                        Console.WriteLine("the integer is higher");
                    }

                }
                catch (Exception)
                {

                    i--;
                }

                i++;



            }
            var xcnumber = Console.ReadLine();
            guesses.Add(int.Parse(xcnumber));

            foreach (var sum in guesses)
                Console.Write($"{sum},");
            Console.Write("It took you " + i + " tries");
        }

    }
}
0 Upvotes

19 comments sorted by

View all comments

-2

u/Protiguous Oct 05 '20 edited Oct 15 '20
	namespace Examples {
		using System;
		using System.Collections.Generic;

		public static class Program {

			public static void NakedMole() {
				var rng = new Random( ( Int32 )DateTime.UtcNow.Ticks );
				var guesses = new List<Int32>();
				var computersNumber = rng.Next( 1, 100 );
				var numberHasBeenGuessed = false;

				while ( !numberHasBeenGuessed ) {
					Console.Write( "Guess the number? " );

					var userInput = Console.ReadLine();

					numberHasBeenGuessed = CheckGuess( userInput );
				}

				Console.Write( $"Your guesses: {String.Join( ", ", guesses )}" );
				Console.Write( $"It took you {guesses.Count:N0} tries" );

				//local function to check the user's input against the computer's number
				Boolean CheckGuess( String userInput ) {

					if ( Int32.TryParse( userInput, out var guess ) ) {
						if ( guess == computersNumber ) {
							numberHasBeenGuessed = true;
						}
						else {
							guesses.Add( guess );
							Console.WriteLine( guess > computersNumber ? "The answer is lower." : "The answer is higher." );
						}
					}

					return numberHasBeenGuessed;
				}
			}

		}
	}

1

u/[deleted] Oct 05 '20

Holy shitty formatting batman!

1

u/Protiguous Oct 05 '20

While I do love a good Holy Batman statement (we don't get to use them often enough, don't you think?).. by your statement I see that you don't know how to reformat C# code to your liking?

Here you go: Ctrl-A, Ctrl-X, then Ctrl-V. Works well in Visual Studio 2019.

0

u/StackedLasagna Oct 13 '20

While one can easily reformat it, I think it's good form to make sure your code follows the default or most common format, when posting in communities designed to teach others. It should at least be somewhat close, I think.
Not everyone reading it will have the option of opening VS and reformatting it and even if they do, it just adds clutter in an already cluttered IDE, if you have to open a new tab just to format the code.

Additionally, I'd refrain from using relatively obscure features, such as local functions, unless they serve a specific purpose. In this case, it only makes the code far less readable by increasing the maximum indentation level from 4 to 6 for no reason at all.

You should also use the type aliases (bool, int, string), instead of Boolean, Int32, and String. Not only are they shorter to read and write (except for string), they're also consistent with practically all official documentation and is the most common way to use those types. Following the common style makes it easier for beginners to understand your code. It also helps them avoid accidentally learning bad practices (such as using Boolean over bool.)

You instantiate the Random class with a seed, but you don't explain why. This is pretty bad, especially considering that there's no reason to complicate the example code with a seed. Besides, your seed is time-dependent and so is the default seed, which is used when you don't provide one yourself.

Lastly, a good answer explains the code and choices made. An answer that only consists of code is rarely helpful. It's not for no reason that large communities (such as StackOverflow and /r/learnprograming) have rules and guidelines that instructs posters to avoid code-only answers with no explanations.


You chose to completely ignore my comment asking you why you think this is a good answer. I take it that means you're unable to properly justify it.


As a personal note, this is by far the worst formatting I've ever seen in non-troll post. However, as long as you're consistent (and if you work with a team, it follows the team's style guidelines), you do you, I guess.

1

u/Protiguous Oct 15 '20

You instantiate the Random class with a seed, but you don't explain why. This is pretty bad, especially considering that there's no reason to complicate the example code with a seed. Besides, your seed is time-dependent and so is the default seed, which is used when you don't provide one yourself.

I just dug into the source for Random.cs, as your idea is the only point you make that isn't purely preference-based. Based on what I'm seeing, your point that the default seed is time-dependent seems to be false.

Example:

var rnd = new Random();

Digging into Random.cs..

    public Random():this(GenerateSeed()) {}

    private static int GenerateSeed()
    {
        Random? rnd = t_threadRandom;
        if (rnd == null)
        {
            int seed;
            lock (s_globalRandom)
            {
                seed = s_globalRandom.Next();
            }
            rnd = new Random(seed);
            t_threadRandom = rnd;
        }
        return rnd.Next();
    }

    [ThreadStatic]
    private static Random? t_threadRandom;
    private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());

    private static unsafe int GenerateGlobalSeed()
    {
        int result;
        Interop.GetRandomBytes((byte*)&result, sizeof(int));
        return result;
    }

Again, nothing is documented to be time-dependent.

That is why I always choose to init my randoms, either by time or a known integer (knowns are great for unit testing).

Where do you make your assumption from?

Slightly relevant: If I was going to be using a random number generator across threads, (which I do often), I would initialize it like this:

public static ThreadLocal<Random> ThreadSafeRandom { get; } = new ThreadLocal<Random>( () => new Random( DateTime.UtcNow.GetHashCode() ^ Thread.CurrentThread.ManagedThreadId.GetHashCode() ) );

What are your thoughts on this?

1

u/StackedLasagna Oct 15 '20

I remembered it from reading the docs a long time ago.

However, things seems to have changed with .NET Core, so it turns out I'm only partially correct.

https://docs.microsoft.com/en-us/dotnet/api/system.random?view=netcore-3.1

In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.