I have a program that displays the days of a month. I want them to be in at least two rows to create a calendar look. Would I do this using a nested loop or the modulo function or something else?
import java.time.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Program
{
public static void main(String[] args) {
ArrayList<LocalDate> dates = new ArrayList<LocalDate>();
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.of(2025, 8, 1);
long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
for (int i=0; i < noOfDaysBetween; i++) {
LocalDate counterdate = startDate.plusDays(i); /*calculates the days from a specific date*
/* For loop iterates through each day, creating and printing each from start date to end date*/
dates.add(counterdate);
//System.out.println(counterdate);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd");
String calformat1 = dtf.format(counterdate);
//System.out.print(calformat1 + " ");
if (i % 7 == 0)
{
System.out.print(calformat1 + " ");
}
System.out.print(" \n");
}
}
}
I tried to wrap the println in a nested for loop but that got me double numbers and no wrapping. Using the modulo in an if statement got me the numbers that matched the statement and that's it.
Do you want it to look something like this?
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 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
You can try this:
public static void main(String[] args) {
ArrayList<LocalDate> dates = new ArrayList<LocalDate>();
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.of(2025, 8, 1);
long noOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
String week = "";
for (int i = 0; i < noOfDaysBetween; i++) {
LocalDate counterdate =
startDate.plusDays(i); /*calculates the days from a specific date*
/* For loop iterates through each day, creating and printing each from start
date to end date*/
dates.add(counterdate);
// System.out.println(counterdate);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd");
String calformat1 = dtf.format(counterdate);
// System.out.print(calformat1 + " ");
if (i % 7 == 0) {
System.out.println(week);
System.out.print("\n");
week = "";
}
week = week.concat(calformat1 + " ");
}
System.out.println(week);
}