是他们在if语句不满足特定要求时循环if语句的任何方式


Console.WriteLine("ALL WORDS YOU TYPE MUST BE LOWERCASE UNLESS STATED OTHERWISE, DO 
YOU UNDERSTAND? n n YES | NO n");
string answer = "undefined";
userInput();
answer = Console.ReadLine();
userInputDone();

if (answer == "yes")
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("nGreat :)n");
Console.ForegroundColor = ConsoleColor.Gray;
} 
else if (answer == "no")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("nTOO BADn");
Console.ForegroundColor = ConsoleColor.Gray;
}

Console.WriteLine("What would you lke to do? n n PLAY | INSTRUCTIONS");

我正在制作一款基于文本的游戏,以适应c#,我该如何循环if语句,以便如果用户没有输入yes或no,它会写"无效输入,再试一次"。并从第一个"Console.WriteLine()">

重新启动

这可能是一个解决方案:

while( true )
{
Console.WriteLine( "Your answer?..." );
var answer = Console.ReadLine();
if (answer == "yes")
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("nGreat :)n");
Console.ForegroundColor = ConsoleColor.Gray;
break;
} 
else if (answer == "no")
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("nTOO BADn");
Console.ForegroundColor = ConsoleColor.Gray;
break;
}    
else 
{
Console.WriteLine("invalid input, try againn");
}
}

使用Do/While Loop.

string answer = "undefined";
do
{
Console.WriteLine("ALL WORDS YOU TYPE MUST BE LOWERCASE UNLESS STATED OTHERWISE, DO YOU UNDERSTAND? n n YES | NO n");
answer = Console.ReadLine().ToLower();
} while (answer != 'yes' && answer != 'no');

您可以使用do while循环:https://www.tutorialsteacher.com/csharp/csharp-do-while-loop

所以你可以输入

do {
// Ask for your input
} while(answer == "no");

这个不需要另一个答案,但是…

将逻辑封装到一个方法中。它是冗长的,但是您将得到知道您编写了一个可重用方法的所有满足:

private static string GetUserInput()
{
var acceptableAnswers = new[] { "yes", "y", "no", "n" };
const string message = "I am Groot? YES | NO";
Console.WriteLine(message);
string input;
while (!acceptableAnswers.Contains(input = Console.ReadLine()?.ToLower()))
{
Console.WriteLine("OMG, you had one job... Read the instructions...");
Console.WriteLine(message);
}
return input;
}

使用

string answer = GetUserInput();
Console.WriteLine("Game over...");
// do what ever

I am Groot? YES | NO
bob
OMG, you had one job... Read the instructions...
I am Groot? YES | NO
y
Game over..

相关内容

  • 没有找到相关文章