我有一种方法可以检查用户是否要玩其他游戏,问题是,如果用户输入了无效的输入,则在正确的输入anotherGame
之后仍设置为Y
>
退出该方法时,即使他们输入了错误的输入而选择了anotherGame
,Y
的值仍然是N
此代码块运行时,anotherGame
无论如何都返回Y
。
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
代码示例:
using System;
public class Program
{
public static void Main()
{
string anotherGame = "y";
while (anotherGame == "y")
{
anotherGame = promptRedo(anotherGame);
Console.WriteLine(anotherGame);
}
}
static String promptRedo(String anotherGame)
{
Console.Write("Would you like to play another game? (Y/N) => ");
String input = Console.ReadLine().ToLower();
if (input.Equals("y"))
{
anotherGame = "y";
}
else if (input.Equals("n"))
{
// get any key from user to exit program
Console.WriteLine();
Console.WriteLine("Thank you for playing!");
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
anotherGame = "n";
Console.WriteLine(anotherGame);
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
return anotherGame;
}
}
答案 0 :(得分:3)
您不需要递归调用,只需删除
promptRedo(anotherGame);
从promptRedo
函数内部的else节开始。
答案 1 :(得分:1)
此函数不需要传递参数。而不是一次又一次地调用函数g只是将其放在循环中:
static String promptRedo()
{
String anotherGame = ""
do
{
Console.Write("Would you like to play another game? (Y/N) => ");
String input = Console.ReadLine().ToLower();
if (input.Equals("y"))
{
anotherGame = "y";
}
else if (input.Equals("n"))
{
// get any key from user to exit program
Console.WriteLine();
Console.WriteLine("Thank you for playing!");
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
anotherGame = "n";
Console.WriteLine(anotherGame);
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
}
} while(anotherGame != "y" && anotherGame != "n")
return anotherGame;
}
答案 2 :(得分:0)
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
在此代码中,您只是调用promptRedo()并在函数末尾返回anotherGame。但是您应该从hintRedo()返回。
您的代码必须如下所示
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
return promptRedo(anotherGame);
}
答案 3 :(得分:0)
您尚未在else块中将“ promptRedo(anotherGame)”方法分配给“ anotherGame”变量。
代替:
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
您应该写:
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
anotherGame = promptRedo(anotherGame);
}