2015-10-13 80 views
0

我正在嘗試製作一個程序,該程序將從用戶處取一個整數並翻轉多次硬幣。但是,當用戶輸入負整數時,程序會遇到「溢出異常」。我怎樣才能讓用戶只能輸入一個正整數?檢查輸入是否存在負整數錯誤

int newLoop = 0; 
     int Number; 
     string answer1 = default(string); 
     string text = default(string); 
     Random newNumber = new Random(); 
     Console.WriteLine("How many times do you want the coin to flip?\n"); 
     string line = Console.ReadLine(); 
     int value; 
     if (int.TryParse(line, out value)) 
     { 
      string[] myValues = new string[value]; 
      while (newLoop < value) 
      { 
       Number = newNumber.Next(0, 2); 
       if (Number == 0) 
       { 
        answer1 = "Tails\n"; 
        myValues[newLoop] = "Tails"; 
       } 
       else 
       { 
        answer1 = "Heads\n"; 
        myValues[newLoop] = "Heads"; 
       } 
       text = " " + answer1; 
       foreach (char u in text) 
       { 
        Console.Write(u); 
       } 
       newLoop++; 
      } 
      Console.ReadLine(); 
      Title(); 
      Question(); 
     } 
     else if (line == "") 
     { 
      Console.WriteLine("\nThat is not a valid number..."); 
      Console.WriteLine("Please try again:"); 
      Console.WriteLine("~enter to continue~"); 
      Console.ReadLine(); 
      coinTask(); 
     } 
     else 
     { 
      Console.WriteLine("\nThat is not a valid number..."); 
      Console.WriteLine("Please try again:"); 
      Console.WriteLine("~enter to continue~"); 
      Console.ReadLine(); 
      coinTask(); 
     } 
+0

就檢查它是大於零?你在哪一行溢出?你調試了你的代碼嗎? –

+0

您可以強制Math.Abs​​輸入爲正值,或者只檢查值是否大於0並給出錯誤消息 – Steve

回答

4

更改線路:

int value; 
if (int.TryParse(line, out value)) 

到:

uint value; 
if (uint.TryParse(line, out value)) 

這樣,你只能接受0和正整數。

0

您可以檢查該值已解析後:

if (int.TryParse(line, out value) && value >= 1)