2015-10-23 63 views
-1

我在程序中使用了try和catch方法,但我沒有規定用戶在輸入不正確的值時輸入的值。例如,用戶輸入一個字符串值,程序表示請輸入一個數字......然後程序不允許該用戶輸入一個新值。我能做什麼?我的代碼在這裏。謝謝。try&catch用於提供值

 try 
     { 
      Console.Write("Please enter column number: "); 
      string str = Console.ReadLine(); 
      int columno = int.Parse(str); 
      if (columno > 20) 
      { 
       Console.WriteLine("please enter a number between 1 and 20"); 
      } 
      else 
      { 
       for (int j = 0; j < columno; j++) 
       { 
        Random rnd = new Random(); 
        for (int i = 0; i < 6; i++) 
        { 

         int rndno = rnd.Next(1, 50); 
         Console.WriteLine(rndno); 

        } 
       } 
      } 

     } 
catch 

     { 
      Console.WriteLine("please enter a number between 1 and 20", "Error"); 
         } 
     Console.ReadLine(); 

    } 



} 
} 
+4

用編程語言標記你的問題。 – csmckelvey

+0

你的意思是你希望用戶被要求輸入值,直到它是一個正確的?或者只是關閉應用程序? –

回答

1

我不知道的語言,可能是C#,但它應該是類似的東西:

Console.Write("Please enter column number: "); 

int columno = 0; 
while(true) { 
    try{ 
     string str = Console.ReadLine(); 
     columno = int.Parse(str); 
     if (columno < 21 && columno > 0) { 
      break; 
     } 
    } 
    catch {} 

    Console.WriteLine("please enter a number between 1 and 20", , "Error");    
} 

    //Rest of the code 

的問題是,您是在整個代碼異常,而不是隻有輸入,所以你趕上它,並繼續所有的代碼。 try內的所有其餘部分未被執行。