r/learncsharp • u/[deleted] • 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");
}
}
}12
u/grrangry Oct 05 '20
You should be able to answer this question yourself.
In the code you have above, which one single line do you think *should* store the user's input? There's one line and it's not where it should be.
I can tell from looking at this code and comparing it to the previous time you asked this question that you moved it, and likely without understanding why. This tells me that you're simply throwing stuff at a wall and seeing what sticks. That's not good debugging.
Like I said in another user's post today, you have to understand three things when writing an application.
What is the data at the start of the application
How are you going to modify that data
What is the expected output at the end
Another way to put it is: you understand where you are, where you're going, and the individual steps it takes to get there.
Understanding point #1 would be knowing what all those variable declarations do at the top of your Main method.
Understanding point #2 would be to understand what the purpose of that while loop is.
Lastly, point #3 is that last little foreach and Console.Write at the end.
4
u/Gathdar21 Oct 05 '20
Inside the while loop right after the incrementation you should add the guess to guesses, you don’t need another Console.Readline() This is also the reason why the program pauses and has you enter the right number twice. So I’d get rid of the line starting ‘int xcnumber’ and move the ‘guesses.Add()’ line inside the loop.
-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
Oct 05 '20
Thanks! I got it working yesterday, but differently. It's interesting to see that solution.
1
1
u/StackedLasagna Oct 05 '20
I'm genuinely curious, why do you think this answers the question or is more than marginally helpful?
1
u/Protiguous Oct 15 '20
Hello again VerticalPasta.
I learn from code examples. Code is generally not as vague as peoples' sentences can be. So code is what I share.
If /u/NakedMoleHamster learned anything from my example, then my goal was accomplished.
1
u/StackedLasagna Oct 15 '20
I also learn mostly from code examples.
Including a proper explanation allows for everyone to learn from your post. Those who learn from code examples can just look at the code, while others can read the explanation, if they need to.
Besides, since you're trying to help a beginner, there's a non-trivial risk that they misunderstand the code or the reasons for doing things in certain ways. This can lead to problems further down the line.
Additionally, your comment doesn't actually answer the question.
OP is asking why his code doesn't work and you haven't explained to him why. If he had asked for ways to solve a specific problem, then your code (even without any explanation) would be much more acceptable and relevant. In the context of OPs question, your comment is little more than spam.A single sentence would be much more helpful (and much quicker for you to post) than your code: "You do not call the
Addmethod on your list, so the list is always empty."This directly answers his question, but you could then go further and provide an example of how to use the
Addmethod, as well as point out any other issues there might be in OP's code.
You could then also provide an example that solves his problem in a more efficient way and it's here that your code would be much more appropriate. However, even then it would be much more helpful to also explain why and how your code solves the problem more efficiently.1
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 ofBoolean,Int32, andString. Not only are they shorter to read and write (except forstring), 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 usingBooleanoverbool.)You instantiate the
Randomclass 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.
0
u/Protiguous Oct 14 '20
That idea that you think you're entitled to my time with a response when you had contributed zero help..
Honestly, I completely forgot about your question as I was more interested in helping someone learn than reply to a trollish question.
If you want to create another zombie-coder, you do you, I guess.
Meanwhile, we'll keep styling to our guidelines (K&R) here.
(Do you really think local functions are obscure? lol, KISS your methods man.)
fyi, we're not in /r/learnprograming/ (or /r/learnprogramming/).
0
u/StackedLasagna Oct 14 '20
Others had already properly helped OP. I saw no need to just repeat their comments.
Your ridiculous attempt at helping is so bad, it cannot possibly be considered help. It’s like if someone is asking why their oven won’t turn on and you reply with a picture of an oven that has been turned on.
I fail to see how anything I’ve said will turn anyone into a zombie-coder.
I did say relatively obscure. Especially to a beginner, as they’re practically never used in the official docs (except for the docs on local functions, lol) or in most beginner teaching material.
Your post is an objectively bad “answer” for multiple reasons that I’ve already outlined.
One thing I did miss earlier, is that it doesn’t even answer the question. That makes it an exceptionally bad answer.Just because we are in a badly maintained community, it doesn’t hurt to look at better communities and adhering to their guidelines where it makes sense.
1
u/Protiguous Oct 15 '20
It’s like if someone is asking why their oven won’t turn on and you reply with a picture of an oven that has been turned on.
That's a seriously bad simile. (And you should know that. I can tell you are not an idiot.)
They gave code with issues.. and asked for help. Without being a style-cop or condescending, I replied with a working solution in the same manner, with code.
Guidelines from other communities can help. They can also hinder. Being more "popular" or more "well-known" doesn't make it right.
1
u/StackedLasagna Oct 15 '20
That's a seriously bad simile.
Yeah, you're right. A more fitting one is if OP had asked why his car overheats and included a picture of his engine and such after popping the hood.
Then your response is similar to just posting a picture of another car's engine, which doesn't overheat, but the car is an entirely different make and model and it doesn't even have the same engine as OP's car.
They gave code with issues.. and asked for help.
Well, that's true... but it ignores literally all the details (there aren't many, but stil...)
OP asked a very specific question related to the code. Refer to my other comment for why I think you didn't actually answer the question.
Guidelines from other communities can help. They can also hinder. Being more "popular" or more "well-known" doesn't make it right.
Surely you can see how adding an explanation helps others? You don't know if OP learns best from examples and if he doesn't it's just spam to him. As I explained in my other comment, adding an explanation ensures everyone can learn from your comment, rather than just a minority.
(I'm taking a guess and assuming that beginners, who learn best without explanations, are an extremely small minority. They probably becomes less of a minority the more experienced the target demographic is.)
2
u/KernowRoger Oct 05 '20
Because you haven't added them to the list anywhere inside the loop. Add them after you assign the guess variable. Also look at int.TryParse so you don't need to catch the exception.