首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java日历程序

Java日历程序
EN

Stack Overflow用户
提问于 2014-02-12 10:51:49
回答 1查看 3.6K关注 0票数 0

我有个项目马上就要交了。我们必须写一个要求一年并打印出日历的程序。我们只能使用一个while、一个for和一个switch循环。(并且没有数组!ugh)我很难弄清楚如何打印出每个月的日期,从第一周的第一天开始,因为大多数月份都不会从周日开始。

代码语言:javascript
复制
import java.util.*;
import java.util.Calendar;
class Lab2 {
    public static void main(String[] args) {
    Scanner user = new Scanner(System.in);
    System.out.print("What year do you want to view? ");
    int year = user.nextInt();
    System.out.printf("%12d\n", year);
    System.out.println();
    boolean leap = isLeap(year);    
    int firstDay = JulianDate(year);
    monthLoop(year, firstDay, leap);
}

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


public static int JulianDate(int year) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.DAY_OF_YEAR, 1);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
    return dayOfWeek;
}

public static void monthLoop(int year, int firstDay, boolean leap) {
    for(int i=1; i <= 12; i++) {
        switch (i) {
            case 1: System.out.printf("%13s\n", "January");
                    break;
            case 2: System.out.printf("%13s\n", "February");
                    break;
            case 3: System.out.printf("%12s\n", "March");
                    break;
            case 4: System.out.printf("%12s\n", "April");
                    break;
            case 5: System.out.printf("%11s\n", "May");
                    break;
            case 6: System.out.printf("%11s\n", "June");
                    break;
            case 7: System.out.printf("%11s\n", "July");
                    break;
            case 8: System.out.printf("%13s\n", "August");
                    break;
            case 9: System.out.printf("%14s\n", "September");
                    break;
            case 10: System.out.printf("%13s\n", "October");
                    break;
            case 11: System.out.printf("%14s\n", "November");
                    break;
            case 12: System.out.printf("%14s\n", "December");
                    break;                      
        }

    System.out.println("S  M  Tu W  Th F  S");


    }

}

}
EN

回答 1

Stack Overflow用户

发布于 2014-02-12 11:05:28

您将获得每月第一天的星期几,如本文所示,然后从那里开始计数器。

How to get the day of the week in Java

例如,如果一周中的某一天是5号,那么您应该在第一个日期前加上4个“空白”。诀窍在于,当您执行mod时,为了确定是否应该有一个新行,它应该是(dayofMonth + firstDayOfWeekOfMonth) %7

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21717625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档