2014-04-01 137 views
0

我有這個作業,我們必須使用嘗試和捕捉,以確保用戶不輸入負數的甜甜圈和非整數數據。當我輸入一個負數時,我得到了try/catch的工作,以便它再次要求輸入甜甜圈的數量,但是當我輸入一個字母而不是數字來表示甜甜圈的數量時,它會出現我爲但它不能再次輸入甜甜圈的數量。如果有人能幫助我,將不勝感激。謝謝。這就是我得到了我的代碼:捕捉輸入錯誤

using System; 
public class CostofDonuts 
{ 
    public static void Main() 
    { 
     string lastName; 
     int number_Of_Donuts; 
     double Total_Cost, Final_Cost; 


     try 
     { 

      // Get user to input their last name 
      Console.Write("Enter customer's last name -> "); 
      lastName = Convert.ToString(Console.ReadLine()); 

      //Get user to input amount of donuts purchased. Ensure that the integer inputted is positive. 
      do 
      { 
       Console.Write("Enter the amount of donuts purchased -> "); 
       number_Of_Donuts = Convert.ToInt32(Console.ReadLine()); 
       if (number_Of_Donuts < 0) 
        Console.WriteLine("Invalid input, number of donuts must be positive"); 
      } while (number_Of_Donuts <= 0); 

      //Calculate cost of donuts 
      if (number_Of_Donuts < 6) 
       Total_Cost = number_Of_Donuts * 0.5; 
      if (number_Of_Donuts <= 15) 
       Total_Cost = number_Of_Donuts * 0.4; 
      else 
       Total_Cost = number_Of_Donuts * 0.3; 

      //Calculate cost with tax 
      if (number_Of_Donuts < 12) 
       Final_Cost = (Total_Cost + 0.25) * 1.13; 
      else 
       Final_Cost = Total_Cost + 0.25; 

      // Output final results 
      Console.WriteLine("{0} bought {1} donuts which came to a total of {2:C}", lastName, number_Of_Donuts, Final_Cost); 
      Console.ReadLine(); 
     } 



     catch (FormatException e) 
     { 
      Console.WriteLine("Input must be a positive integer"); 
     } 

     catch (Exception e) 
     { 
      Console.WriteLine("Input must be a positive integer"); 
     } 
    } 
} 
+0

你的try/catch需要在一個循環內;現在,如果拋出一個異常,它會跳出do/while循環並離開該方法。 –

回答

1

您需要使用try/catch你的循環內,以保持繼續

do 
{ 
     Console.Write("Enter the amount of donuts purchased -> "); 
     try 
     { 
      number_Of_Donuts = Convert.ToInt32(Console.ReadLine()); 
     } 
     catch (Exception) 
     { 
      Console.WriteLine("Invalid input, number of donuts must be positive"); 
      number_Of_Donuts = 0; 
     } 

} while (number_Of_Donuts <= 0); 
0

可以使用int.TryParse

do 
    { 
     Console.Write("Enter the amount of donuts purchased -> "); 
     if(int.TryParse(Console.ReadLine(), out number_Of_Donuts) && number_Of_Donuts >= 0) 
      break; 
     Console.WriteLine("Invalid input, number of donuts must be positive"); 
    } while (number_Of_Donuts <= 0); 
0
 do 
     { 
      Console.Write("Enter the amount of donuts purchased -> "); 
      Int.TryParse(Console.ReadLine(), out number_Of_Donuts); 
      if (number_Of_Donuts < 0) 
       Console.WriteLine("Invalid input, number of donuts must be positive"); 
     } while (number_Of_Donuts <= 0);