Java로 Calendar 만들기 (2)

janeljs·2020년 12월 4일
6
post-thumbnail

구현하고 싶은 기능

  • 년도와 월을 입력으로 받아와 달력 출력
  • 일정 등록 (date, event, location, guests)
  • 날짜로 일정 검색
  • 파일로 일정 저장 (다시 실행했을 때도 이전에 등록한 정보 검색 가능)

구조

1. Prompt

package janeljs.calendar;


import java.util.Scanner;

public class Prompt {

	public void printMenu() {
		System.out.println("+----------------------+");
		System.out.println("| 1. 일정 등록");
		System.out.println("| 2. 일정 검색");
		System.out.println("| 3. 달력 보기");
		System.out.println("| h. 도움말 q. 종료");
		System.out.println("+----------------------+");
		System.out.print("SELECT> ");
	}

	public void runPrompt(Scanner sc) {
		final String COMMAND_KEYS = "🔮 command (1, 2, 3, h, q)";

		printMenu();
		Command cmds = new Command();
		
		boolean isLoop = true;
		while (isLoop) {
			
			String cmd = sc.nextLine();
			switch (cmd) {
			case "1":
				cmds.cmdRegister(sc);
				System.out.println(COMMAND_KEYS);
				break;
			case "2":
				cmds.cmdSearch(sc);
				System.out.println(COMMAND_KEYS);
				break;
			case "3":
				cmds.cmdPrintCalendar(sc);
				System.out.println(COMMAND_KEYS);
				break;
			case "h":
				printMenu();
				break;
			case "q":
				isLoop = false;
				System.out.println("Have a nice day!");
				break;
			}
		}
		
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Prompt prompt = new Prompt();
		prompt.runPrompt(sc);
		sc.close();

	}

}

2. Calendar

package janeljs.calendar;


public class Calendar {
	public static final int[] LAST_DAYS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	public static final int[] LEAP_YEAR_LAST_DAYS = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

	public static boolean isLeapYear(int year) {
		if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
			return true;
		} else {
			return false;

		}
	}

	public static int getFirstDay(int year, int month) {
		final int START_YEAR = 1970;
		final int START_DAY_OF_THE_WEEK = 4;
		int firstDay=0;

		int daySum = 0;
		for (int i = START_YEAR; i < year; i++) {
			if(!isLeapYear(i)) {
				daySum+=365;
			}
			else {
				daySum+=366;
			}
			
		}

		for (int i = 1; i < month; i++) {
			if(!isLeapYear(year)) {
				daySum += LAST_DAYS[i-1];
			}
			else {
				daySum += LEAP_YEAR_LAST_DAYS[i-1];
				
			}
		}

		firstDay = (START_DAY_OF_THE_WEEK+daySum) % 7;
		
		return firstDay;
	}

	public static void printCalendar(int year, int month) {

		System.out.printf("     🌼%4d년 %d월🌼\n", year, month);
		System.out.println(" SU MO TU WE TH FR SA");
		System.out.println(" --------------------");

		int count = 0;

		int firstDay = getFirstDay(year, month);
		
		for (int i = 0; i < firstDay; i++) {
			System.out.print("   ");
			count++;
		}

		int lastDay = getLastDay(year, month);
		for (int i = 1; i <= lastDay; i++) {
			System.out.printf("%3d", i);
			count++;
			if (count % 7 == 0) {
				System.out.println();
			}
		}
		System.out.println();
		System.out.println();
	}

	public static int getLastDay(int year, int month) {
		int lastday = 0;
		if (isLeapYear(year)) {
			lastday = LEAP_YEAR_LAST_DAYS[month - 1];
		} else {
			lastday = LAST_DAYS[month - 1];
		}

		return lastday;
	}
}

3. PlanItem

package janeljs.calendar;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class PlanItem {
	String format;
	String plan;
	String location;
	ArrayList<String> guests;

	public PlanItem() {
		guests = new ArrayList<>();
	}
	
	
	
	public PlanItem(String plan, String location, ArrayList<String> guests) {
		this.plan = plan;
		this.location = location;
		this.guests = guests;
	}

	public void planItem(Scanner sc, Date date) {
		System.out.println("✔️ Add Event");
		System.out.print("EVENT> ");
		plan = sc.nextLine();

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		format = formatter.format(date);
		System.out.println("📆 " + format + " : " + plan + "\n" + "Successfully Registered \n");
	}

	public void planPlace(Scanner sc) {
		System.out.println("🗺️ Add location");
		System.out.print("LOCATION> ");
		location = sc.nextLine();

	}

	public void planGuest(Scanner sc) {

		System.out.println("🗺️ Add guests (press q to quit)");

		while (true) {
			System.out.print("GUEST> ");
			String guest = sc.nextLine();

			if (guest.equals("q")) {
				System.out.println("GUESTS: " + guests);
				System.out.println();
				break;
			}
			guests.add(guest);
		}

	}
}

4. Command

package janeljs.calendar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Scanner;

public class Command {
	HashMap<Date, PlanItem> planSave;

	public Command() {
		planSave = new HashMap<>();
		File f = new File("plan.dat");
		if (!f.exists()) {
			return;
		}
		try {
			Scanner sc = new Scanner(f);
			while (sc.hasNext()) {
				String line = sc.nextLine();
				String[] words = line.split(",");
				Date date = fromStringtoDate(words[0]);
				String plan = words[1];
				String location = words[2];
				String[] strGuests = Arrays.copyOfRange(words, 3, words.length);
				ArrayList<String> alGuests = fromStringtoArrayList(strGuests);
				PlanItem p = new PlanItem(plan, location, alGuests);
				planSave.put(date, p);
			}
			sc.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public ArrayList<String> fromStringtoArrayList(String[] strGuests) {
		ArrayList<String> alGuests = new ArrayList<>();
		for (String x : strGuests) {
			String temp = x.replace("[", "").replace("]", "").replace(" ", "");
			alGuests.add(temp);
			
		}
		return alGuests;
	}

	public void cmdRegister(Scanner sc) {

		System.out.println("\n[CREATE] Enter a date (yyyy-MM-dd).");
		System.out.print("DATE> ");
		String strDate = sc.nextLine();
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd").parse(strDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		PlanItem newplan = new PlanItem();
		System.out.println();
		newplan.planItem(sc, date);
		newplan.planPlace(sc);
		System.out.println();
		newplan.planGuest(sc);

		planSave.put(date, newplan);

		try {
			FileWriter fw = new FileWriter("plan.dat", true);
			fw.write(newplan.format + "," + newplan.plan + "," + newplan.location + "," + newplan.guests + "\n");
			fw.close();
		} catch (IOException e) {
			System.out.println("An error occured.");
			e.printStackTrace();
		}

	}

	public Date fromStringtoDate(String strDate) {
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd").parse(strDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	public void cmdSearch(Scanner sc) {
		System.out.println("[SEARCH] Enter a date (yyyy-MM-dd).");
		System.out.print("DATE> ");
		String searchDate = sc.nextLine();
		Date sdate = fromStringtoDate(searchDate);
		PlanItem result = planSave.get(sdate);
		System.out.println("💖 Event: " + result.plan);
		System.out.println("🗺️ Location: " + result.location);
		int i = 1;
		System.out.println("👨‍👩‍👦‍👦 Guest List");
		for (String x : result.guests) {
			System.out.println("- Guest" + i + ": " + x);
			i++;
		}
		
		System.out.println();

	}

	public void cmdPrintCalendar(Scanner sc) {

		System.out.println("📆 Enter a year.");
		System.out.print("YEAR> ");
		int year = sc.nextInt();

		System.out.println("🈷 Enter a month.");
		System.out.print("MONTH> ");
		int month = sc.nextInt();

		if (year < 0 || month > 12 || month < 1) {
			System.out.println("❗ 유효한 값이 아닙니다.");
			year = sc.nextInt();
			month = sc.nextInt();
		}

		Calendar.printCalendar(year, month);

	}

}

5. plan.dat

일정을 처음 등록하면 plan.dat파일이 생성되고, 새로 등록할 때마다 아래와 같은 형태로 추가된다. 파일에 정보를 저장해 놓았기 때문에 프로그램을 종료했다가 다시 실행해도 일정을 검색할 수 있다.

2020-12-06,Finance Team Standup,Sinchon,[Tom, Julia]
2020-12-15,Sales Weekly Kick-off,Paris,[Andrew, Jane]


후기

드디어 완강 + 프로젝트 완료!😎 금방 끝날 줄 알았는데 강의를 안 보고 차근차근 구현하려니 생각보다 시간이 오래걸렸다. 그래도 미션 조건 외에 내가 추가하고 싶었던 기능들도 구현하고, 추가 클래스와 메서드들도 만들어 봤더니 조금 더 자바 프로그래밍이 익숙해진 것 같다.

+) eclipse console 창에 이모지가 예쁘게 출력되었으면 좋겠다😢

3개의 댓글

comment-user-thumbnail
2020년 12월 8일

완전 이쁘게 잘 만들엇네요 🤩🤩

1개의 답글
comment-user-thumbnail
2020년 12월 15일

Thanks a lot for sharing!JOKER123

답글 달기