[英]Trying to make it in c# where the user enters their age and it tells them what year they were born in
[英]Trying to make a menu that keeps repeating if the user enters something invalid
這里完全是初學者,昨天我人生中第一次開始學習編程,所以請不要判斷!
我正在嘗試制作一個程序,允許用戶輸入視頻游戲的名稱和分數,然后根據要求顯示這些分數。 我正在嘗試制作菜單。 我注意到如果用戶在沒有輸入任何數字的情況下按 Enter 鍵,程序就會崩潰,我想避免這種情況,但我被卡住了。 如果我按回車,它不會崩潰。 但是,如果我輸入 1 或 2,菜單仍然會繼續運行,如果我在此之后不輸入任何內容就按 Enter,那么它會崩潰嗎? 我迷路了。
namespace videogaems
{
class Program
{
static void Main(string[] args)
{
menu();
}
static void menu()
{
int option = 0;
Console.WriteLine("Select what you want to do: ");
Console.WriteLine("1- add game");
Console.WriteLine("2- show game rating");
bool tryAgain = true;
while (tryAgain)
{
try
{
while (option != 1 || option != 2)
{
option = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
}
catch (FormatException)
{
option = 0;
}
}
}
如果字符串無法轉換為整數, Convert.ToInt32(Console.ReadLine())
將拋出異常。 相反,您應該使用int.TryParse
,它接受一個string
和一個設置為轉換值的out
參數(如果成功)。 它返回一個bool
,指示它是否成功。
例如,只要int.TryParse
失敗,下面的代碼就會循環,當它成功時, userInput
將包含轉換后的數字:
int userInput;
while (!int.TryParse(Console.ReadLine(), out userInput))
{
Console.WriteLine("Please enter a whole number");
}
然而,另一種選擇是簡單地使用Console.ReadKey()
,它返回一個ConsoleKeyInfo
對象,該對象表示用戶按下的鍵。 然后我們可以只檢查鍵字符的值(並忽略任何無效的鍵)。
例如:
static void Menu()
{
bool exit = false;
while (!exit)
{
Console.Clear();
Console.WriteLine("Select what you want to do: ");
Console.WriteLine(" 1: Add a game");
Console.WriteLine(" 2: Show game rating");
Console.WriteLine(" 3: Exit");
ConsoleKeyInfo userInput = Console.ReadKey();
Console.WriteLine();
switch (userInput.KeyChar)
{
case '1':
// Code to add a game goes here (call AddGame() method, for example)
Console.Clear();
Console.WriteLine("Add a game was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '2':
// Code to show a game rating goes here (call ShowRating(), for example)
Console.Clear();
Console.WriteLine("Show game rating was selected");
Console.WriteLine("Press any key to return to menu");
Console.ReadKey();
break;
case '3':
// Exit the menu
exit = true;
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.