Попробуй и поймай блоки не бросая ничего - PullRequest
0 голосов
/ 14 апреля 2020

Я создал блок ArgumetException catch, и он ничего не выдает, когда я ввожу что-то, что он должен перехватить ... как это исправить? Например, если я ввожу возраст водителя в 15 или 81 год, он все равно не будет пойман и рассчитывает окончательную премию. Я также хотел бы войти в их штат проживания, который не Огайо или Мичиган, и мой блок улова ничего не ловит. Я не знаю, можете ли вы понять, что я пытаюсь сказать, но если вы скопируете и вставите это в свою IDE и попробуете запустить ее самостоятельно, я думаю, вы поймете это немного больше.

Здесь это код

class Program
    {
        static void Main(string[] args)
        {
            CarInsurance create = new CarInsurance();
            try
            {
                Console.Write("Enter the age of the driver: ");
                int age = Convert.ToInt32(Console.ReadLine());
                Console.Write("Enter the state the driver lives in: ");
                string residence = Convert.ToString(Console.ReadLine());
                create.PremiumCalculate(age, residence);
            }
            catch (FormatException) // catches if user inputs a string instead of a value
            {
                Console.WriteLine("You didn't enter a numeric value for the age of the driver!");
            }
        }
    }
    class CarInsurance
    {
        public int driverAge { get; set; } // gets and sets driver age
        public string residency { get; set; } // gets and sets residency
        public int totalPremium;

        public int GetPremium() // gets the premium ***readonly***
        {
            return totalPremium;
        }
        public void PremiumCalculate(int age, string residency) // main method for CarInurance class
        {
            int premiumOhio = 100;
            int premiumMichigan = 250;
            try
            {
                if (residency == "MI")
                {
                    int total = (100 - age) * 3 + premiumMichigan;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
                if (residency == "OH")
                {
                    int total = (100 - age) * 3 + premiumOhio;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
            }
            catch (ArgumentException)
            {
                if (age < 16 && age > 80)
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
                if (residency != "OH" && residency != "MI")
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
            }
        }
    }

Последний блок try-catch внизу кода - это то, с чем у меня проблема.

...