我正在尝试检查方法调用中的输入是否有效。 然后我需要该方法来接收输入,确认其真或假。 如果为 false,则循环并再次请求输入,如果为 true,则返回到 Main() 方法。 我只是在每次输入后继续循环相同的 console.write 行。不遵循我的“while”循环。 所以我无法判断它是否调用了 bool 方法并返回。
public static void Main(string[] args)
{
InputFuelType();
Console.WriteLine("The Fuel Type Is {0}", InputFuelType());
}
public static string InputFuelType()
{
Console.WriteLine("Please Enter A Fuel Type, 3 Characters Starting With An Upper Case Letter Followed By 2 Numbers");
Console.ReadLine();
while (!IsValid(InputFuelType()))
{
Console.WriteLine("Is Not A Correct Fuel Type, Please Enter A Correct Fuel Type ");
Console.ReadLine();
}
return InputFuelType();
}
public static bool IsValid(string id)
{
if (id.Length != 3)
return false;
if (!char.IsAscii(id[0]))
return false;
if (!char.IsDigit(id[1]) || !char.IsDigit(id[2]))
return false;
else
return true;
}
你正在递归 - 在我看来你的
InputFuelType
似乎不确定它是否应该只是“获取一些输入”或“获取一些输入并验证它”(你以两种方式使用它)。除了其他任何事情之外,您在最后无条件地调用该方法本身,因此永远不会结束。
我会像这样重组它:
public static string InputFuelType()
{
Console.WriteLine("Please Enter A Fuel Type, 3 Characters Starting With An Upper Case Letter Followed By 2 Numbers");
string fuelType = Console.ReadLine();
while (!IsValid(fuelType))
{
Console.WriteLine("Is Not A Correct Fuel Type, Please Enter A Correct Fuel Type ");
fuelType = Console.ReadLine();
}
return fuelType;
}
根本不需要递归。