1
1

More than 1 year has passed since last update.

【Java】カレンダー作成

Last updated at Posted at 2022-03-05

 1月までJavaをしばらく触っていなかったため、過去にRubyで作ったことのあるプログラムをJavaで作ってみることにしました。今回はカレンダー作成問題です。

アウトプットのネタに困ったらこれ!?
↑こちらの記事を参考にして問題を解いています。

【Ruby】カレンダー作成問題を解く

問題は、次のような形式で今月のカレンダーを表示させることです。

     April 2013
Su Mo Tu We Th Fr 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

 今回Javaで作ってみたプログラムはこちらです。今月だけでなく、他の年の他の月も確認したかったため、年と月の変数のみ切り分けました。

package example;

import java.util.Calendar;
import java.util.Collections;

public class CreateCalendar {

	public static void main(String[] args) {
		Calendar cl = Calendar.getInstance();
		
		int thisYear = cl.get(Calendar.YEAR); //今年
		int thisMonth = cl.get(Calendar.MONTH); //今月(1月=0、2月=1であるため配列monthの添字に使用)
		outputCalendar(thisYear,thisMonth);
		
		//他の年、他の月の場合の確認用
		System.out.println("\n");
		int otherYear = 2013; //西暦を入力
		int otherMonth = 4; //月を入力
		outputCalendar(otherYear,otherMonth - 1);
		
	}
	
	public static void outputCalendar(int inputYear, int inputMonth) {
		Calendar cl = Calendar.getInstance();
		
		String[] month = {"January","February","March","April","May","June",
				"July","August","September","October","November","December"};
		String[] week = {"Su","Mo","Tu","We","Th","Fr","Sa"};
		
		int firstDay = 1; //月の初日
		//月の初日の曜日(日曜日=1、月曜日=2であるため-1をして配列weekの添字に使用)
		cl.set(inputYear,inputMonth,firstDay);
		int firstDayWeek = cl.get(Calendar.DAY_OF_WEEK) - 1; 
		int lastDay = cl.getActualMaximum(Calendar.DAY_OF_MONTH); //月の最終日

		System.out.print("     " + month[inputMonth] + " " +  inputYear); //年と月を出力
		System.out.println(); 

		//カレンダーの曜日を出力
		for (int i = 0; i < week.length; i++) {
			System.out.printf("%2s ",week[i]);
		}
		System.out.println();
		//初日が何曜日かに合わせて空白を出力
		System.out.print(String.join("", Collections.nCopies(firstDayWeek, "   ")));
		//日付を出力
		for (int i = firstDay; i <= lastDay; i++) {
			System.out.printf("%2d ",i);
			if ((firstDayWeek + i) % 7 == 0) {
				System.out.println();
			}			
		}
	}
}

こちらが出力結果です。

     March 2022
Su Mo Tu We Th Fr 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 

     April 2013
Su Mo Tu We Th Fr 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 
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1