Почему цикл Do Пока не останавливается после того, как условие не выполнено? - PullRequest
1 голос
/ 02 октября 2019

Я написал код, который получает данные пользователя о датах начала и окончания и проверяет их действительность. В приведенном ниже коде у меня есть 2 цикла do.. while. Один для даты начала, а другой для даты окончания. Когда первый цикл выполняется и условие не выполняется, программа не переходит к другому циклу do while. Было бы полезно, если бы я мог получить решения для этой проблемы.

int year, startMonth, endMonth, startDay, endDay; 
    boolean checkStartDate = false, checkEndDate = false;
    Scanner input = new Scanner (System.in);

    //checking Start Date
    do
    {   
    checkStartDate = false;
    System.out.print("Enter the year: ");
    year = input.nextInt();
    System.out.print("Enter the start month: ");
    startMonth = input.nextInt();
    System.out.print("Enter the start day: ");
    startDay = input.nextInt(); 

        switch (startMonth) 
        {
          case 1:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
          break;

          case 2:
       if(startDay <= 28)
        {
            checkStartDate = true;
        }
            break;

          case 3:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }

            break;

          case 4:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 5:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 6:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 7:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 8:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 9:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 10:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 11:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 12:
        if(startDay <= 31)
        {
            checkStartDate = true;
            return;     
        }
          default:
          checkStartDate = false;
          System.out.println("Try again and enter a valid date \n");
        }   
        checkStartDate = false;

    } while (checkStartDate = true);

    //checking End Date

    do
    {   
    checkEndDate = false;
    System.out.print("Enter the year: ");
    year = input.nextInt();
    System.out.print("Enter the start month: ");
    endMonth = input.nextInt();
    System.out.print("Enter the start day: ");
    endDay = input.nextInt(); 

        switch (endMonth) 
        {
          case 1:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }

        else
        {
            checkEndDate = false;
            System.out.println("Print a valid start day");
        }
          break;

          case 2:
       if(endDay <= 28)
        {
           checkEndDate = true;
        }
            break;

          case 3:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }

            break;

          case 4:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 5:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 6:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 7:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 8:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 9:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 10:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 11:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 12:
        if(endDay <= 31)
        {
            checkEndDate = true;
            return;
        }

          default:
            checkEndDate = false;
            System.out.println("Try again and enter a valid date \n");
        }   
        checkEndDate = false;

    } while (checkEndDate = true);

    System.out.println("correct ");

Ответы [ 2 ]

2 голосов
/ 02 октября 2019
while (checkEndDate = true)

Вы присваиваете значение checkEndDate как истинное, поэтому цикл будет повторяться всегда. Вы, вероятно, имели в виду:

while (checkEndDate == true)

Это сравнивает два значения. Но поскольку у вас уже есть логическое значение, сравнение не требуется:

while (checkEndDate)

Обратите внимание, что вы можете значительно сократить объем кода, комбинируя похожие случаи. Например:

case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
    if(startDay <= 31)
    {
        checkStartDate = true;
    }
    break;

То же самое для месяцев с 30 днями.

Вам также следует написать метод checkDate(), чтобы один и тот же код не записывался дважды.

0 голосов
/ 02 октября 2019

вы добавили checkStartDate= false & checkEndDate = false; конец каждого цикла do while. который не требуется.

Обновите условие while как while (checkStartDate);, так как оно оценивается с помощью логического значения.

ниже - рабочий код

int year, startMonth, endMonth,startDay, endDay;логическое checkStartDate = false, checkEndDate = false;Вход для сканера = новый сканер (System.in);

    //checking Start Date
    do
    {   
    checkStartDate = false;
    System.out.print("Enter the year: ");
    year = input.nextInt();
    System.out.print("Enter the start month: ");
    startMonth = input.nextInt();
    System.out.print("Enter the start day: ");
    startDay = input.nextInt(); 

        switch (startMonth) 
        {
          case 1:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
          break;

          case 2:
       if(startDay <= 28)
        {
            checkStartDate = true;
        }
            break;

          case 3:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }

            break;

          case 4:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 5:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 6:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 7:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 8:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 9:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 10:
        if(startDay <= 31)
        {
            checkStartDate = true;
        }
            break;

          case 11:
        if(startDay <= 30)
        {
            checkStartDate = true;
        }
            break;

          case 12:
        if(startDay <= 31)
        {
            checkStartDate = true;
            return;     
        }
          default:
          checkStartDate = false;
          System.out.println("Try again and enter a valid date \n");
        }   
       // checkStartDate = false;

    } while (checkStartDate);

    //checking End Date

    do
    {   
    checkEndDate = false;
    System.out.print("Check End Date... ");
    System.out.print("Enter the year: ");
    year = input.nextInt();
    System.out.print("Enter the start month: ");
    endMonth = input.nextInt();
    System.out.print("Enter the start day: ");
    endDay = input.nextInt(); 

        switch (endMonth) 
        {
          case 1:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }

        else
        {
            checkEndDate = false;
            System.out.println("Print a valid start day");
        }
          break;

          case 2:
       if(endDay <= 28)
        {
           checkEndDate = true;
        }
            break;

          case 3:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }

            break;

          case 4:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 5:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 6:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 7:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 8:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 9:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 10:
        if(endDay <= 31)
        {
            checkEndDate = true;
        }
            break;

          case 11:
        if(endDay <= 30)
        {
            checkEndDate = true;
        }
            break;

          case 12:
        if(endDay <= 31)
        {
            checkEndDate = true;
            return;
        }

          default:
            checkEndDate = false;
            System.out.println("Try again and enter a valid date \n");
        }   
      //  checkEndDate = false; 

    } while (checkEndDate);

    System.out.println("correct ");
...