[英]C# Code Repeating User Input Prompt After Calling Method
我正在嘗試制作一個程序,要求用戶輸入,如果用戶選擇對自己的選擇不滿意,則可以選擇重新啟動。 如果他們選擇選項,然后最后選擇是,則該程序可以完美運行,但是如果他們選擇否,再次選擇屬性,然后選擇是,則提示用戶選擇是否再次接受。 該程序讀取:
有你的屬性點!
你接受這些嗎? 鍵入1表示是,鍵入2表示否。如果否,則可以再次選擇:
1
你接受這些嗎? 鍵入1表示是,鍵入2表示否。如果否,則可以再次選擇:
1
按任意鍵繼續...
這是代碼:
while (true)
{
Console.Write("Do you accept these? Type 1 for Yes, Type 2 for No. If No you can choose again: ");
areYouHappyWithChoices = Console.ReadLine();
if (!UInt32.TryParse(areYouHappyWithChoices, out validChoices))
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (validChoices > 2 || validChoices < 1)
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (areYouHappyWithChoices == "2")
chooseAttributePoints(); //this method contains the whole routine
else
break;
}
因此,我測試了您的代碼,它對我來說很好。 看來您的chooseAttributePoints()
方法中還有一個額外的Console.ReadLine()
,因此在調用chooseAttributePoints()
之后必須兩次輸入選擇。 請檢查以確保這是問題所在。
備注:
我還對您的代碼進行了一些重組,以使代碼更具可讀性,並減少了冗余。
int validChoices;
do
{
Console.WriteLine("do some logic ......"); // replace this line with your chooseAttributePoints() method ...
Console.Write("Do you accept these? Type 1 for Yes, Type 2 for No. If No you can choose again: ");
// read input until user gets it right and enters a valid number ...
var areYouHappyWithChoices = Console.ReadLine();
while (!int.TryParse(areYouHappyWithChoices, out validChoices) || validChoices < 1 || validChoices > 2)
{
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
areYouHappyWithChoices = Console.ReadLine();
}
} while (validChoices != 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.