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
You have 2 problems:
1. Your code doesn't compile because you try to bind P1Choice
twice.
2. You ask for input twice in your else
case.
To fix 1., you have to remove int
from the second occurrence of P1Choice
, the one in the else
case.
To fix 2., you have to remove Console.readKey()
in the else
case.
Besides, your code will be easier to read if you use else if
clauses instead of just if
clauses.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
if (P1Choice == 1) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 4");
} else {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Furthermore, I'd recommend you to use a switch
clause instead of this many if
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.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (P1Choice == 1) {
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
CenterWrite("You have chosen Default Empire 4");
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Instead of having fixed Strings, you can concatenate the value of P1Choice
.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (1 <= P1Choice && P1Choice <= 4) {
CenterWrite("You have chosen Default Empire " + P1Choice);
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}