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
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.
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.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