Printing a Calendar from Given Month/Year

后端 未结 4 984
南笙
南笙 2021-01-25 03:36

I\'m working on a Java assignment and it involves printing a calendar after the user specifies a month and a year. I cannot use the Calendar or GregorianCalendar classes. My pro

相关标签:
4条回答
  • 2021-01-25 04:01

    The problem is that your indexes are messed up. What that means is that you are starting your months and days of the weak from 1 instead of 0. However here

    h = (1 + (int)(((month + 1) * 26) / 10.0) + year + (int)(year / 4.0) + 6 * (int)(year / 100.0) + (int)(year / 400.0)) % 7
    

    the %7 at the end makes it start at 0! This causes the loop

    for (int i = 0; i < h - 1; i++)
      System.out.print("   ");
    

    to be

    for (int i = 0; i < -1; i++)
      System.out.print("   ");
    

    since h is 0 for Saturday.

    To fix this issue, you should start all indexes in your functions with 0. Then when you get user input indexed at 1, simply subtract 1 and pass it into your functions. Then you also won't have that blank entry in front of all your arrays (which by the way should be static finals at the top of the class).

    0 讨论(0)
  • 2021-01-25 04:04

    I Know you got the answer. But here is quick fix (Sorry its kinda hacky) that you can incorporate to correct your indexes for Saturday without making many changes to your code.

    System.out.println("Su Mo Tu We Th Fr Sa");
            int xx = h == 0 ? 7 : h; // Correct the index for Saturday.
            for (int i = xx; i > 1; i--) // Reversing the loop condition
                System.out.print("   ");
            for (int i = 1; i <= numDays; i++) {
                System.out.printf("%2d ", i);
                if (((i + h - 1) % 7 == 0) || (i == numDays))
                    System.out.println();
            }
    
    0 讨论(0)
  • 2021-01-25 04:15

    This will fix the leap year issue

    if ((((i + h) % 7 == 0) || (i == numDays) && leap(year)))
    
    0 讨论(0)
  • 2021-01-25 04:16

    Your code will have the same issue for every month that starts with a Saturday. This means that the problem is probably in this line -

    for (int i = 0; i < h - 1; i++)
      System.out.print("   ");
    

    Having h as 7 instead of 0 here will fix it for you. You can either fix that here or you may need to start h from 1 to 7 instead of 0 to 6 and make other required changes of course.

    0 讨论(0)
提交回复
热议问题