我的尝试没有抓住我的错误消息,,,

时间:2018-04-22 18:53:40

标签: c#

当我运行我的代码时,我可以输入任何字符,它会给我一个字母等级,这是不应该的。我错过了什么?

namespace ProjException
/* Include exception handling techniques with the traditional averaging program. 
 * Allow the user to input multiple sets of scores.
 * Ensure that only numeric values are entered and that values fall between 0 and 100. 
 * Calculate the average for each set of values. 
 * Test the result to determine whether an A, B, C, D, or F should be recorded. The scoring rubric is as follows: A—90–100; B—80–89; C—70–79; D—60–69; F < 60.
 * Your solution should include exception-handling techniques with a minimum of three appropriate catch clauses.
 */
{
    class Program
    {
        static void Main(string[] args)
        {
            // Variables Declared
            int grade = 0;
            int total = 0;
            int count = 0;
            double average;
            string letterGrade = "F";

            while (grade != -99)
            {
                try
                {
                   Console.Write("Enter a Grade 0-100 -99 to quit: ");
                   grade = int.Parse(Console.ReadLine());

                   if ((grade != -99 && grade < 0) || grade > 100)
                        throw new ArgumentOutOfRangeException();

                   if (grade != -99)
                   {
                        total += grade;
                        count++;
                   }
                }
                catch (FormatException e)
                {
                    Console.WriteLine("Grade must be a number");
                }
                catch (ArgumentOutOfRangeException e)
                {
                    Console.WriteLine("Grade must be between 0 and 100 or -99 to quit");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Some other error occurred");
                    Console.WriteLine(e);
                }

                average = (double)total / count;

                if (average >= 90)
                    letterGrade = "A";
                else if (average >= 80)
                    letterGrade = "B";
                else if (average >= 70)
                    letterGrade = "C";
                else if (average >= 60)
                    letterGrade = "D";
                else
                    letterGrade = "F";

                Console.WriteLine("Your letter grade is " + letterGrade);
                Console.ReadKey();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

当您发现异常(工作正常)时,您不会改变流程。程序将在尝试catch块后继续,并最终达到等级的输出。这里的一种方法是在catch块中使用continue,以使循环结束当前迭代并从头开始下一个迭代。