這裏構建一個簡單的應用程序;問題的方法:流不是預期的
靜態硬幣類
public static void SetUpCoins() {
coin1 = new Coin();
coin2 = new Coin();
}
public static void PlayConsole() {
SetUpCoins();
OutputWinner();
}
public static void OutputWinner() {
if (coin1.ToString() == "Heads" && coin2.ToString() == "Heads") {
Console.WriteLine("You threw Heads - you win");
++point_player;
} else if (coin1.ToString() == "Tails" && coin2.ToString() == "Tails") {
Console.WriteLine("You threw Tails - I win");
++point_comp;
} else {
Console.WriteLine("You threw Odds");
WaitForKey_ConsoleOnly("Press any key to throw again");
PlayConsole();
}
Console.WriteLine("You have {0} points and the computer has {1} points", point_player, point_comp);
if (WantToPlayAgain_ConsoleOnly()) { // ask user if they want to play again; return bool
PlayConsole();
}
}
private static bool WantToPlayAgain_ConsoleOnly() {
string input;
bool validInput = false;
do {
Console.Write("Play Again? (Y or N): ");
input = Console.ReadLine().ToUpper();
validInput = input == "Y" || input == "N";
} while (!validInput);
return input == ("Y");
}
如果false
是從WantToPlayAgain_ConsoleOnly()
返回程序不會退出。下面是輸出,這也解釋了我的問題的一個例子:
爲什麼,當WantToPlayAgain_ConsoleOnly
是假的,做節目無法通過控制playConsole
方法然後退出。而不是這種重複。
OutputWinner
完成運行後,它跳轉到PlayConsole
,然後返回到OutputWinner
的else語句 - 不知道爲什麼。
請把WantToPlayAgain_ConsoleOnly() – Adil
的代碼,你怎麼可以做'新幣()''時爲Coin'靜態? – V4Vendetta
你的問題是基本的代碼結構。具體來說,問題是在「賠率」案例中引發的遞歸 - 斷點,逐步完成,您將會看到到底發生了什麼。 –