while loop not working?
Can someone find why this loop isn't working? I'm new to C#.
while (move == "r" || move == "s" || move == "f")
{
C开发者_运维技巧onsole.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("\nYou have reloaded, press enter for Genius");
Console.ReadLine();
break;
case "s":
Console.Write("\nYou have shielded, press enter for Genius");
Console.ReadLine();
break;
case "f":
Console.Write("\nYou have fired, press enter for Genius");
Console.ReadLine();
break;
default:
Console.Write("\nInvalid move, try again\n\n");
break;
}
}
Probably because move is initialized inside the loop and is probably null or an empty string since I can't see the code before the loop I'm assuming its not initialized.
My suggestion is to use a boolean flag that is set as such
bool done = false;
while (!done)
{
// do work
if (move == finalMove) // or whatever your finish condition is
done = true; // you could also put this as a case inside your switch
}
Jesus is right, suggest you accept his answer. Here's how you can rewrite the code.
do
{
Console.Write("\nEnter your move: ");
move = Console.ReadLine();
switch (move)
{
case "r":
Console.Write("\nYou have reloaded, press enter for Genius");
Console.ReadLine();
break;
case "s":
Console.Write("\nYou have shielded, press enter for Genius");
Console.ReadLine();
break;
case "f":
Console.Write("\nYou have fired, press enter for Genius");
Console.ReadLine();
break;
default:
Console.Write("\nInvalid move, try again\n\n");
break;
}
}
while (move == "r" || move == "s" || move == "f");
Note however that if you get something besides "r", "s", or "f" you will print Invalid move, try again
and then exit your loop (they can't try again). You might instead want to assign a key (maybe "q" for quit) that does terminate the loop and change your while
condition to something like
while (move != "q");
精彩评论