+ 3

Bool + while + if

I'm having a bit of a hard time understanding this: (Ex:) int a = 0; bool x = false; while (x == false) { Console.Write("choose a number: "); x = int.TryParse(Console.ReadLine()), out a); if (x == false) Console.WriteLine("invalid input"); } Here's my questions: 1. Why do you declare that bool x is false? Why not true? 2. How does the code know that it should start over when someone answers with an invalid value? 3. Do you need the combination of those three datatypes or can you use only one of them or others? 3. The while and if has the same condition but it's the If that brings forward the "invalid value"-message, why?

30th Oct 2019, 11:20 AM
Linnea Nordén
Linnea Nordén - avatar
2 odpowiedzi
+ 1
1. First iteration x = false because x is false, the statement x==false is true so you can enter the while loop if a valid input is given x becomes true, the method TryParse returns true if the conversion was succes full. nothing is printed . The while-loop ends here because x is no longer equal to false. if the input was invalid x becomes false, the method TryParse returns false if the conversion was not succesfull. Then the if-statement x == false is true. And the console prints the line "invalid input" So the while-loop continues to ask for a new input because the statement x==false is still true. 2. The while loop continues to repeat it self as long as the condition of the while is true. This is how the while-loop works. The while loop start at { and ends at }. The code between { and } is repeated. 3. There are several ways to get a valid input. This is one of them. You need the boolean value to check if the conversion was valid. You need the integer to hold the result value. 4. The Console.WriteLine is the line that is responsible for printing "invalid input". This line is in the if-statement so that is why the code in the if-statement is printing that line.
30th Oct 2019, 12:40 PM
sneeze
sneeze - avatar
+ 2
Thanks sneeze!
30th Oct 2019, 2:45 PM
Linnea Nordén
Linnea Nordén - avatar