Need help on returning values
Hello, I've made a simple function that changes a value to whatever number has been entered by the user, as you can see in the image attached to this thread.
It seems to work just fine.
What I would like to do though is to have it check to see that if someone didn't input number, then it would repeat the input request for a number until the user gets it right.
Or in clearer words, if
int.TryParse(userEntered, out int parsedNumber);
fails, then the user would be sent right back to the line var userEntered = Console.ReadLine();
.
Now, my idea would be to do something like this:
However, there are is one error code it gives when running it:
I'm a bit confused, shouldn't there be a parsedNumber
variable when it runs while (!int.TryParse(userEntered, out int parsedNumber));
?
Any help would be greatly appreciated.
6 Replies
it's because you're declaring it inside the while loop condition, which puts it in the scope of the while loop and it doesn't exist outside of it
you can declare it before the while loop then assign to it with
out parsedNumber
instead of out int parsedNumber
your loop syntax is also incorrect, C# uses braces and not indentation so your loop is technically empty and the indented code always runs after the loop exits
if a specific example helps, this is how it should look:
Firstly, C# is not Python, indentation doesn't matter whatsoever. If you want both lines to run inside of the loop, both need to be within the braces of the loop
Secondly, you have a semicolon after the
while ();
which terminates it
is not equal to
but rather
Similarly,
is not the same as
but rather, the same as
Thank you both! Very helpful.
It's true, I do come from Python and need to learn C#. It's had some challenges so far.
So I added the code as such:
It turns out that while when I type an integer it works, but when I type a word for a number like say "three" it returns the value
0
.
At no point does it ask me to re-enter an input if I don't enter an integer.are you sure that's the code you're running, like the build is successful and everything? because when i copy and paste it into my IDE it works fine:

int.TryParse
doesn't parse the word form of numbers, only actual digitsThe code actually does work, I messed up.
Thank you so much! @Jimmacle !