Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to make a java method, that will print out a calendar. The method gets a year and a month value. Then it gets how many days were in that month.

I then have a loop, that creates first spaces, if the 1. of the month does not start on monday. The problem is that it prints it out like this:
MO  TU  WE  TH  FR  SO  SA
                 1   2   3   4   5   6   7  
 8   9  10  11  12  13  14
15  16  17  18  19  20  21
22  23  24  25  26  27  28
29  30  31


How would I know which days are still in the first week, and which have to be line broken to be printed in the second row?

What I have tried:

This is my code

static void izpisKoledarja(int leto, int mesec){
    java.time.YearMonth yearMonth = java.time.YearMonth.of(leto, mesec);
    int steviloDni = yearMonth.lengthOfMonth();
    int prviDan = java.time.LocalDate.of(leto, mesec, 01).getDayOfWeek().getValue();

    System.out.println("MO  TU  WE  TH  FR  SO  SA");

    String initialSpace = "";
    for (int i = 0; i < prviDan - 1; i++) {
        initialSpace += "    ";
    }
    System.out.print(initialSpace);

    for (int dayOfMonth = 1; dayOfMonth <= steviloDni; ) {
        for (int j = 0; j < 7 && (dayOfMonth <= steviloDni); j++) {
            System.out.printf("%2d  ", dayOfMonth);
            dayOfMonth++;
        }
        System.out.println();
    }
}
Posted
Updated 19-Mar-21 5:04am
Comments
Richard MacCutchan 19-Mar-21 10:31am    
You need to check what day of the week each date is, rather than using a simple loop. So when you have printed the date for a Sunday, you start a new line.

1 solution

Try the following:
Java
java.time.YearMonth yearMonth = java.time.YearMonth.of(leto, mesec);
int steviloDni = yearMonth.lengthOfMonth();
int prviDan = java.time.LocalDate.of(leto, mesec, 01).getDayOfWeek().getValue();
//
// add code to print the month and year details here
//
System.out.println("MO  TU  WE  TH  FR  SO  SA");

String initialSpace = "";
for (int i = 0; i < prviDan - 1; i++) {
    initialSpace += "    ";
}
System.out.print(initialSpace);

for (int dayOfMonth = 1; dayOfMonth <= steviloDni; ) {
    System.out.printf("%2d  ", dayOfMonth);
    // get the day of the week and if it is Sunday, terminate this line
    prviDan = java.time.LocalDate.of(leto, mesec, dayOfMonth).getDayOfWeek().getValue();
    if (prviDan == java.time.DayOfWeek.SUNDAY.getValue()) {
        System.out.println();
    }
    // increment to the next day of the month
    dayOfMonth++;
}
System.out.println(); // always print a blank line at the end
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900