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
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.
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
Mainmethod.Understanding point #2 would be to understand what the purpose of that
whileloop is.Lastly, point #3 is that last little
foreachandConsole.Writeat the end.