javafor-loopwhile-looplogic

Loops and comparing variable values


A user inputs a year and it is stored in year . And a method is called that calculates and returns the next year that would fall on the same day of the week. The month and day do not change only the year. In this case the month is Jan and the day is 1.

/**
 * @param theYear the year given
 */
public int yearSync(int theYear)
{
   int month = 1;
   int day = 1;
   int year = theYear;

   int aMonth = 1;
   int aDay = 1;
   int aYear = year++;

   Date d1 = new Date(month, day, year);
   Date d2 = new Date(aMonth, aDay, aYear);

   boolean valid = false;       

   while (!valid)
   {
      if(d1.getDayOfWeek().equals(d2.getDayOfWeek)))//another class provided is used to 
      {                                             //calc what day of the week it is
         System.out.println(aYear); //prints the year
      }                             //that falls on the same week day as the input year
      else
      {
         aYear++;
      }
   }
   return aYear;
}

Not asking for answer just want to know where my error in logic is and what I can do to change my thought process when going about problems such as these. In case there is any confusion, an example would be if I entered 2014, the year returned would be 2020; they both fall on Wednesday.

Edit: changed loop type.


Solution

  • Your loop for (int i = 0; i <= i++; i++) will never stop ...

    The first time through, i is set to 0, and the condition is i < i++, which will change the value of i to i +1, but the comparison will succeed.

    So the first time through the loop, the value of i is 1. At the end of the loop it will increment it because of the i++ (to be the value 2), and then it will compare it again with i <= i++ which will pass, but will also set i to be 3.

    So, the value i will be 1, 3, 5, 7, .... in your loops.

    This loop condition is pretty bizarre, but, that's not really the problem.... because it is essentially the same as:

    while (true) {...}
    

    The odd part is that when you actually find a year that has the same yad-of-week, you don't then increment the year, i.e. the aYear++ never changes once you find the first match, and then you just repeat the same System.out.println(...) forever.

    But again, this is all somewhat meaningless because you never change the date value d2 inside the loop.....

    What you want is something like:

    while(true) {
        aYear++;
        Date d2 = new Date(aMonth, aDay, aYear);
        if (d1.getDayOfWeek().equals(d2.getDayOfWeek)))//another class provided is used to 
        {                                             //calc what day of the week it is
            System.out.println(aYear); //prints the year
            return aYear;
        }
    }