[英]not all code paths return a value? help needed
我正在制作ac#控制台游戏,尝试解决当前链接到静态int ResetGame()部分的此错误时遇到了麻烦。 显然,并非所有代码路径都返回值。 我该如何解决?
static int ResetGame()
{
Console.WriteLine("Welcome to Tactical Space Cheese Racer");
Console.WriteLine("");
Console.WriteLine("Press any Key to continue");
Console.ReadLine();
Console.Clear();
Console.WriteLine("Please enter the number of players that wish to play (2-4) : ");
int NoOfPlayers = int.Parse(Console.ReadLine());
Console.WriteLine("");
for (int i = 0; i < NoOfPlayers; i++)
{
Console.WriteLine("");
Console.WriteLine("Please enter the name of the player: " + i + i++);
Console.WriteLine("");
players[i].Name = Console.ReadLine();
players[i].Pos = 0;
}
}
如果您需要查看它来解决问题,我还有更多代码可用
您遇到的问题是您的方法应该返回一个int
而不返回它。
如果您不想返回任何内容,则应声明您的方法是一个void
方法。
static void ResetGame()
{
}
我可以从您的代码中得出结论,这可能是您的意图。 因此,使您的方法void
,您将不会有任何问题。
此外,我必须对您设置球员人数的方式做一个旁注。 如果用户输入一个非整数值,您将得到一个您无法处理的异常。 除此之外,如果用户输入一个大于4的整数,那就不行了。 话虽如此,但您应同时注意上述两项。
int numberOfPlayers = -1;
Console.WriteLine("Please enter the number of players that wish to play (2-4) : ");
// The method Int32.TryParse parses the input and check if it
// can be represented as a 32-bit integer number.
// If parse succeeds, then the value is assigned to numberOfPlayers
// and the method returns true. Otherwise, it returns false.
while(!Int32.TryParse(Console.ReadLine()), out numberOfPlayers) &&
!(numberOfPlayers>2 && numberOfPlayers<4))
{
Console.WriteLine("Please enter a valid number between (2-4): ");
}
更新
Idle_Mind在他的评论中指出了以下几点:
我会说他需要返回球员人数。
如果是这样,您只需在方法的右花括号之前添加以下内容即可:
return numberOfPlayers;
我想你会继续我的名字。 如果愿意,只需将变量名更改为您的即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.