int year = scanner.nextInt();
System.ou"> int year = scanner.nextInt();
System.ou">
117.info
人生若只如初见

Java实现简单的万年历

????????????Java??:

import java.util.Scanner;
public class Calendar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("?????:");
int year = scanner.nextInt();
System.out.print("?????:");
int month = scanner.nextInt();
printCalendar(year, month);
}
public static void printCalendar(int year, int month) {
// ??????????????
int firstDayOfWeek = getFirstDayOfWeek(year, month);
// ????
System.out.println(" ?  ?  ?  ?  ?  ?  ?");
// ????
for (int i = 0; i < firstDayOfWeek; i++) {
System.out.print("    ");
}
// ????
int daysInMonth = getDaysInMonth(year, month);
for (int i = 1; i <= daysInMonth; i++) {
System.out.printf("= ", i);
if ((i + firstDayOfWeek) % 7 == 0) {
System.out.println();
}
}
}
public static int getFirstDayOfWeek(int year, int month) {
int totalDays = 0;
// ???1900?1?1??????????
for (int i = 1900; i < year; i++) {
totalDays += isLeapYear(i) ? 366 : 365;
}
for (int i = 1; i < month; i++) {
totalDays += getDaysInMonth(year, i);
}
// ??????????????
return (totalDays + 1) % 7;
}
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
public static int getDaysInMonth(int year, int month) {
if (month == 2) {
return isLeapYear(year) ? 29 : 28;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
}

?????,??????????,?????????????

??:?????????????,???????????????,???2???29?,???2???28??

未经允许不得转载 » 本文链接:https://www.117.info/ask/fedf5AzsLBgBVB1M.html

推荐文章

  • java字符串去掉空格的方法有哪些

    Java 字符串去掉空格的方法有以下几种: 使用 String 类的 trim() 方法,该方法会去掉字符串两端的空格。 String str = " Hello World ";
    String trimmedSt...

  • java调用父类的方法有哪些

    在Java中,调用父类的方法有以下几种方式: 使用super关键字:使用super关键字可以调用父类的方法。可以通过super.method()的方式调用父类的非私有方法,也可以通...

  • java怎么判断字符串是否为纯数字

    可以使用正则表达式来判断一个字符串是否为纯数字。下面是一个示例代码:
    public class Main {
    public static void main(String[] args) {
    Strin...

  • java子类调用父类方法是什么

    Java子类调用父类方法是通过使用super关键字来实现的。super关键字可以用来调用父类的构造方法、成员变量和成员方法。通过super关键字,子类可以在自己的方法中调...

  • oracle中distinct的用法详解

    在Oracle中,DISTINCT关键字用于从查询结果中去除重复的行。它可以应用于SELECT语句中的一个或多个列,以确保查询结果中不包含重复的行。
    DISTINCT关键字的...

  • iOS 项目中的version和build 详解

    在iOS开发中,version和build是两个重要的属性,用于标识和管理应用程序的不同版本。
    Version(版本号)是用户可见的,用于标识应用程序的不同版本。它通常...

  • js对字符串和数字进行加法运算的一些情况

    在JavaScript中,对字符串和数字进行加法运算可能会产生以下几种结果: 如果加法运算符的两个操作数都是数字,那么它们将被简单地相加: let num1 = 10;
    le...

  • 微信小程序的运行机制与安全机制解决方案详解

    微信小程序的运行机制与安全机制解决方案如下: 运行机制: 微信小程序的运行机制基于微信客户端,用户通过微信客户端打开小程序,小程序将在微信客户端内部运行...