我是C#的新手,但我知道Java相當不錯。我可能錯過了一些簡單的東西,因爲剛剛接觸這種特定的語言,我只是不知道。我試圖讓一個while循環重複直到用戶選擇Q.循環退出正常,但是它的代碼在它停止之前重複3次以提示用戶進行選擇。爲什麼會發生?因爲使用的是Console.Read()
,這將處理輸入流中的下一個字符,它包括從當用戶按下Enter
的\n
和\r
字符C#我的while循環重複3次,然後它提示另一個選擇
class MainClass
{
public static void DisplayMenu() {
Console.WriteLine("What would you like to do?");
Console.WriteLine("(D)eposit");
Console.WriteLine("(W)ithdraw");
Console.WriteLine("(C)alculateInterest");
Console.WriteLine("(S)howBalance");
Console.WriteLine("(Q)uit");
Console.WriteLine("************************************");
Console.WriteLine("Make choice by entering first letter of choice,");
Console.WriteLine("then press ENTER key:");
}
static void Main(string[] args) {
Account account = new Account();
char choice;
double amount = 0.0;
Console.WriteLine("************************************");
Console.WriteLine("Welcome to Bernard's Bodacious Bank!");
Console.WriteLine("************************************");
Console.WriteLine("We have opened your account");
DisplayMenu();
choice = Char.ToUpper((char)Console.Read());
while (!choice.Equals('Q')) {
DisplayMenu();
choice = Char.ToUpper((char)Console.Read());
}
account.ShowTransactions();
Console.ReadKey();
}
}
可能被拋出某處未處理的異常。您可以添加一個try/catch塊或附加您的調試器,並確保它捕獲所有clr異常。 – Igor
如果你告訴他們按回車你應該使用Console.ReadLine()。您也可以在重新繪製菜單後按下Enter鍵來清除屏幕。 – numbtongue