Skip to Content
TechJava Simple Calendar

Java Simple Calendar

public class SimpleCalendar { // Main method, will be executed when the program is run public static void main(String[] args) { // Calls the createCalendar method // with 31 days(one month) and the first day being Wednesday (3) // 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday SimpleCalendar.createCalendar(31, 3); } public static void createCalendar(int days, int firstDay) { // Array of String // representing days of the week in Japanese ("Sun", "Mon", "Tue", etc.) String[] daysOfWeek = {"日", "月", "火", "水", "木", "金", "土"}; // String representing the space symbol // make it easier to notice String spaceSymbol = "|"; // Enhanced for loop // Iterates through the daysOfWeek array // make up the first row of the calendar for (String day : daysOfWeek) { System.out.print(day + spaceSymbol); } // Create a new line after the days of week header System.out.println(); // Print leading spaces (underscores) // for the days before the first day of the month // This loop runs 'firstDay' times // to align the start of the month correctly for (int i = 0; i < firstDay; i++) { System.out.print("_" + "_" + spaceSymbol); } // Loop to print the days of the month // starting from 1 until the specified number of days (31 here) for(int i = 1; i <= days; i++) { // If the day is a single digit // prepend a '0' for better alignment // (e.g., 01, 02, etc.) if(i < 10) { System.out.print("0"); } // Print the current day followed by the space symbol System.out.print(i + spaceSymbol); // After printing 7 days (a full week), move to the next line // The condition checks if (current day number + first day offset) is divisible by 7 // For example, if the first day is Wednesday (3), the first week will have 3 padding empty slots // padding slot, padding slot, padding slot, (1 + 3) % 7 = 4, (2 + 3) % 7 = 5, (3 + 3) % 7 = 6, (4 + 3) % 7 = 0 (next line) // (5 + 3) % 7 = 1, (6 + 3) % 7 = 2, (7 + 3) % 7 = 3, (8 + 3) % 7 = 4, (9 + 3) % 7 = 5, (10 + 3) % 7 = 6, (11 + 3) % 7 = 0 (next line) // (12 + 3) % 7 = 1, (13 + 3) % 7 = 2, (14 + 3) % 7 = 3, (15 + 3) % 7 = 4, (16 + 3) % 7 = 5, (17 + 3) % 7 = 6, (18 + 3) % 7 = 0 (next line) // (19 + 3) % 7 = 1, (20 + 3) % 7 = 2, (21 + 3) % 7 = 3, (22 + 3) % 7 = 4, (23 + 3) % 7 = 5, (24 + 3) % 7 = 6, (25 + 3) % 7 = 0 (next line) // (26 + 3) % 7 = 1, (27 + 3) % 7 = 2, (28 + 3) % 7 = 3, (29 + 3) % 7 = 4, (30 + 3) % 7 = 5, (31 + 3) % 7 = 6 if ((i + firstDay) % 7 == 0) { System.out.println(); } // Output: // // 日|月|火|水|木|金|土| // __|__|__|01|02|03|04| // 05|06|07|08|09|10|11| // 12|13|14|15|16|17|18| // 19|20|21|22|23|24|25| // 26|27|28|29|30|31| } } }
Last updated on
Do not shoot this.