2014-04-01 188 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);