2015-11-23 18 views
0

嗨我有一個程序,允許用戶從選項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) 
     { 

     } 

回答

0

您可以使用一個簡單的if聲明是這樣的:

... 
string userChoiceSTR = Console.ReadLine(); 

if(userChoiceSTR != "1" && userChoiceSTR != "2" && userChoiceSTR != "3") 
{ 
    Console.WriteLine("You need to provide a value between 1 and 3"); 
    //Handle the case of invalid input (e.g. return) 
} 
... 
0

1)如果用戶輸入某個值或者不是你正在檢查。但是你不檢查它是否是整數。你需要確保他輸入了整數。在try塊內移動Convert語句。

  try 
      { 
       userChoice = Convert.ToInt16(userChoiceSTR); 
       Options(); 
      } 
      catch 
      { 
       Console.WriteLine("Did not put valid value. Please Select a menu: "); 
       Main_Menu(); 
      } 

現在,你需要確保他在1和3之間進入在你塞納里奧,我會建議使用開關的情況下。

private void Options() 
{ 

    switch(userChoice) 
    { 
     case 1: 
      Console.Clear(); 
      Console.WriteLine("Welcome....................."); 
      Console.ReadLine(); 
      break; 
     case 2: 
      Console.Clear(); 
      Console.WriteLine("Help........................."); 
      Console.ReadLine(); 
      break; 
     case 3: 
      break; 
     default: 
      //Code to handle other values. 
      break; 
    } 


} 
0

使用TryParse代替Convert方法來驗證數字輸入。如果用戶輸入不是數字,則不會拋出異常。相反,它將返回一個布爾值false。例如,

//Declare the boolean variable: 
bool input = false; 

string string1 = ""; 

//Get the user input and attempt to parse to an int: 
string1 = Console.Readline(); 
input = int.TryParse(string1, out num1);