[Java] I tried to display the calendar on the Eclipse console using Java.

1 minute read

For memo only. ・It was easy to forget that the month is set from “0 to 11” ⇒ “January to December” when cal.set(int year,int month-1,1). ・ Cal.getActualMaximum(Calendar.DATE) can be used to find out how many days are in xxxx year and xx month. ・The day of the week and the date were stored using an array.

image.png

・Class that creates and outputs a calendar ‥ package foo; import java.util.Calendar; public class Calmaker {

public void Makecal(int year,int month){ Calendar cal = Calendar.getInstance(); //int weekday = cal.get(Calendar.DAY_OF_WEEK); //System.out.println(weekday);

int days[][] = new int[6][7];

System.out.println(“Sun Moon Fire Wednesday Thursday Saturday”); int row = 0;

// loop from one day to the last day for (int i = 1; i <= cal.getActualMaximum(Calendar.DATE); i++) { // set date to object cal.clear(); cal.set(year, month-1, i); // Month is specified from 0 to 11, so we will increment it by -1. int weekday = cal.get(Calendar.DAY_OF_WEEK);

// extend date days[row][weekday-1] = i; //System.out.println(days[row][weekday-1]);

if(weekday %7 ==0) { row ++; } }

// output for (int k = 0; k <6; k++) { for (int j = 0; j <7; j++) {

String res = String.valueOf(days[k][j]);

if(days[k][j]==0) { System.out.print(“ “); }else if(days[k][j] <10) { System.out.print(“ “+ res + “”);

}else if(days[k][j] >= 10) { res = res+” “; System.out.print(res); } if(j == 6) { System.out.println(“\r\n”); } } } } } ・Main class

package foo;

import java.util.Scanner;

public class Makecal {

public static void main(String[] args) { // TODO auto-generated method stub System.out.println(“Enter the year in 4 digits”); Scanner sc1 = new Scanner(System.in); System.out.println(“Enter the month 1-12”); Scanner sc2 = new Scanner(System.in);

int year = sc1.nextInt(); int month = sc2.nextInt(); System.out.println(“AD”+year+”year” + month +”month”); System.out.println(“”);

Calmaker clm = new Calmaker(); clm.Makecal(year,month); }

}

image.png

the end.