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 code below but I only came up with results relating to breaking while loops or the solution to be not to put it in a while loop
int P1Choice = int.Parse(Console.ReadLine());
while (true)
{
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
int P1Choice = int.Parse(Console.ReadLine());
}
}
I understand that I can't declare the local parameter "P1Choice" in this scope, but then are there any other methods to achieve the output of the code in such that when the user doesn't input the corresponding choices, that it loops again?
I hope this is what you need. The possibles values are in the List "list" and it loops until the answer is one of the possible values:
You have 2 problems: 1. Your code doesn't compile because you try to bind
P1Choice
twice. 2. You ask for input twice in yourelse
case.To fix 1., you have to remove
int
from the second occurrence ofP1Choice
, the one in theelse
case.To fix 2., you have to remove
Console.readKey()
in theelse
case.Besides, your code will be easier to read if you use
else if
clauses instead of justif
clauses.Furthermore, I'd recommend you to use a
switch
clause instead of this manyif
clauses. But let that be a lecture for another day. :)You can make further improvements. In all cases, you call
Console.WriteLine("")
so move it outside.Instead of having fixed Strings, you can concatenate the value of
P1Choice
.You just have to use readline inside your while loop and in else also do break. It should work this way:
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.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 4if
s, since this would be the accepted way of implementing user input choice.Good luck!
One option can be to create method and keep calling until valid input comes:
and in your main program:
Here is code based on the post you deleted :