[英]method not returning correct value
我有一種方法可以檢查用戶是否要玩其他游戲,問題是,如果用戶輸入了無效的輸入,那么在正確輸入之后, 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;
}
}
您不需要遞歸調用,只需刪除
promptRedo(anotherGame);
從內部的promptRedo
功能的else部分promptRedo
。
此函數不需要傳遞參數。 而不是一遍又一遍地調用函數,只需將其放在循環中即可:
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;
}
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
promptRedo(anotherGame);
}
在這段代碼中,您只是調用hintRedo()並在函數末尾返回anotherGame。 但是您應該從hintRedo()返回。
您的代碼必須如下所示
else
{
Console.WriteLine("ERROR: Invalid input (Y/N) only!");
return promptRedo(anotherGame);
}
您尚未在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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.