I am currently looking for a solution for this c# console application function
I tried searching for a method for creating a while loop that can terminate for the co
If you want to exit a while
loop only when certain statements are met, then that's what you should state when entering your loop.
I would use a boolean
to know whether the user made a right choice or not.
bool right_choice = false;
int P1Choice = int.Parse(Console.ReadLine());
while(!right_choice) {
switch(P1Choice) {
case 1:
right_choice = true;
{case 1 code};
break;
case 2:
right_choice = true;
{case 2 code};
break;
case 3:
right_choice = true;
{case 3 code};
break;
case 4:
right_choice = true;
{case 4 code};
break;
default:
break;
}
if (!right_choice) {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
P1Choice = int.Parse(Console.ReadLine());
}
}
}
This way as soon as the user makes a correct choice you exit the loop.
Note that I changed your code to use a switch case
instead of 4 if
s, since this would be the accepted way of implementing user input choice.
Good luck!