嗨我有一個程序,允許用戶從選項1,2和3是userChoice中進行選擇。但是,當我輸入一個高於3的數字或一個字母而不是數字時,程序會崩潰或退出。我想知道是否有驗證規則可以使用,因此只能輸入數字1至3。驗證規則只需要輸入數字
int userChoice;
static void Main(string[] args)
{
new Program().Welcome();
}
public void Welcome()
{
Console.WriteLine(" HELLO");
Console.ReadLine();
Main_Menu();
}
private void Main_Menu()
{
Console.WriteLine("1). Welcome");
Console.WriteLine("2). Help Facilities");
Console.WriteLine("3). Exit");
string userChoiceSTR = Console.ReadLine();
if (!string.IsNullOrEmpty(userChoiceSTR))
{
userChoice = Convert.ToInt16(userChoiceSTR);
try
{
Options();
}
catch
{
Console.WriteLine("Did not put any value. Please Select a menu: ");
Main_Menu();
}
}
else
{
Console.WriteLine("Did not put any value. Please Select a menu: ");
Main_Menu();
}
}
private void Options()
{
if (userChoice == 1)
{
Console.Clear();
Console.WriteLine("Welcome.....................");
Console.ReadLine();
}
if (userChoice == 2)
{
Console.Clear();
Console.WriteLine("Help.........................");
Console.ReadLine();
}
if (userChoice == 3)
{
}