Java練習:可視化日曆小程序

public static void main(String[] args) throws ParseException {
        System.out.println("請輸入日期(格式 2020-8-12)");
        Scanner scanner = new Scanner(System.in);
        String date = scanner.nextLine();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = dateFormat.parse(date);

        Calendar c = new GregorianCalendar();
        c.setTime(parse);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int dayMax = c.getActualMaximum(Calendar.DATE);
        c.set(Calendar.DAY_OF_MONTH, 1);
        System.out.println("日\t一\t二\t三\t四\t五\t六");
        // 控制每月1號星期對齊
        for (int i = 0; i < c.get(Calendar.DAY_OF_WEEK) - 1; i++) {
            System.out.print("\t");
        }
        //輸入日曆
        for (int i = 0; i < dayMax; i++) {
            //判斷如果打印的日期和輸入日期相同後面加*
            if (c.get(Calendar.DAY_OF_MONTH) == day) {
                System.out.print(c.get(Calendar.DAY_OF_MONTH) + "*" + "\t");
            } else {
                System.out.print(c.get(Calendar.DAY_OF_MONTH) + "\t");
            }
            //如果日期爲星期六換行
            if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                System.out.println();
            }
            //當前日期+1
            c.add(Calendar.DAY_OF_MONTH, 1);
        }
    }

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章