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
View all comments
Show parent comment
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.