Почему мое ключевое слово continue в цикле do-while не работает? - PullRequest
2 голосов
/ 19 апреля 2019

Я только начинаю изучать C #, и я пытаюсь создать действительно простую программу о знании DayOfWeek определенной даты.Ключевое слово continue в цикле do-while не работает для проверки ошибок.

Я попытался сделать другой способ проверки ошибок, включив условия непосредственно в цикл while, но мне любопытно, почемуПродолжить не работает.

class Program
    {
        static void Main(string[] args)
        {
            int yearInput, monthInput, dateInput;
            Console.WriteLine("We can tell you any day of any date");
            bool correctInput;


            //the problem starts at dateInput request (the third do while loop)

            do { Console.WriteLine("\nSet a year :");
                correctInput = int.TryParse(Console.ReadLine(), out yearInput);

                if (!correctInput)
                {
                    Console.WriteLine("Incorrect Input!");

                }
            }

            while (!correctInput);

            // this part is where is starts

            do
            {
                Console.WriteLine("\nSet a month :");
                correctInput = int.TryParse(Console.ReadLine(), out monthInput);
                if (!correctInput || monthInput < 1 || monthInput > 12)
                {
                    Console.WriteLine("Incorrect Input!");

                }
            }
            while (!correctInput || monthInput < 1 || monthInput > 12);



            do
            {
                Console.WriteLine("\nSet a date :");
                correctInput = int.TryParse(Console.ReadLine(), out dateInput);
                if (!correctInput || dateInput > 31 || dateInput < 1)
                {
                    Console.WriteLine("Incorrect Input!");

                }
                else
                {

                    if (dateInput > DateTime.DaysInMonth(yearInput, monthInput))
                    {
                        Console.WriteLine("The date doesn't reach that many!");
                        continue;


                    }

                }
            } while (!correctInput || dateInput > 31 || dateInput < 1);

            DateTime day = getDayofDate(yearInput, monthInput, dateInput);
            Console.WriteLine("\nIt is {0}.", day.DayOfWeek);
            Console.ReadKey();

        }
        static public DateTime getDayofDate (int year, int month, int day)
        {
            return new DateTime(year, month, day);
        }


    }

Я ожидаю, что цикл будет повторяться после того, как он встретит ошибку, но вместо этого будет показано исключение ArgumentsOutOfRangeException.

1 Ответ

3 голосов
/ 19 апреля 2019

continue работает , но все же проверяет состояние цикла.Однако условие false - цикл останавливается!Чтобы исправить это, вы можете установить correctInput на false, а также удалить continue - потому что после if больше нет операторов для выполнения (компьютер автоматически переходит к следующей итерации):

        do
        {
            Console.WriteLine("\nSet a date :");
            correctInput = int.TryParse(Console.ReadLine(), out dateInput);
            if (!correctInput || dateInput > 31 || dateInput < 1)
            {
                Console.WriteLine("Incorrect Input!");

            }
            else
            {

                if (dateInput > DateTime.DaysInMonth(yearInput, monthInput))
                {
                    Console.WriteLine("The date doesn't reach that many!");
                    correctInput = false; // Makes one more iteration of the loop
                }

            }
        } while (!correctInput || dateInput > 31 || dateInput < 1);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...