java 日历算法_Java实现 蓝桥杯VIP 算法提高 任意年月日历输出

算法提高 任意年月日历输出

时间限制:1.0s 内存限制:512.0MB

已知2007年1月1日为星期一。

设计一函数按照下述格式打印2007年以后(含)某年某月的日历,2007年以前的拒绝打印。

为完成此函数,设计必要的辅助函数可能也是必要的。其中输入为年分和月份。

样例输入:

2007 1

样例输出:

Calendar 2007-01

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

样例输入:

2010 9

样例输出:

Calendar 2010-09

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

注意:短线“-”个数要与题目中一致,否则系统会判为错误。

c72fba13d6155439f54904c02008bafe.png

数据规模和约定

输入数据中每一个数的范围。

例:年 2007-3000,月:1-12。

import java.util.Scanner;

public class 日历 {

public static boolean isLeap(int year) {

boolean flag = false;

if(year % 4 == 0 && year % 100 != 0)

flag = true;

else if(year % 400 == 0)

flag = true;

else

flag = false;

return flag;

}

public static int getDay(int month, int year) {

int day = 0;

if (month == 2) {

if (isLeap(year))

day = 29;

else

day = 28;

} else if (month < 8) {

if(month % 2 == 0)

day = 30;

else

day = 31;

} else {

if(month % 2 == 0)

day = 31;

else

day = 30;

}

return day;

}

public static int getFirst(int month, int year) {

int first = 0;

int distance = year - 2007;

int day = 0;

while (distance / 4 >= 1) {

day += (365 * 4 + 1);

distance -= 4;

}

int count = 0;

while (distance > 0) {

if (count == 1)

day += 366;

else

day += 365;

count++;

distance--;

}

int fre = 0;

if(isLeap(year))

fre = 31 + 29;

else

fre = 31 + 28;

int mon[] = {0, 0, 31, fre, fre+31, fre+61, fre+92, fre+122, fre+153, fre+184, fre+214, fre+245, fre+275};

day += mon[month];

first = day % 7;

return first+1;

}

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

int year = sc.nextInt();

int month = sc.nextInt();

sc.close();

if(year < 2007)

return;

int day = getDay(month, year);

int firstDay = getFirst(month, year);

if(month < 10)

System.out.println("Calendar " + year + " - 0" + month);

else

System.out.println("Calendar " + year + " - " + month);

for (int i = 0; i < 21; i++)

System.out.print("-");

System.out.print("\n");

System.out.println("Su Mo Tu We Th Fr Sa ");

for (int i = 0; i < 21; i++)

System.out.print("-");

System.out.print("\n");

int count = 0;

if(firstDay != 7)

for (int i = 0; i < firstDay; i++) {

System.out.print(" ");

count++;

}

for (int i = 1; i <= day; i++) {

if(i < 10)

System.out.print(" " + i + " ");

else

System.out.print(i + " ");

count++;

if(count % 7 == 0)

System.out.print("\n");

}

System.out.print("\n");

for (int i = 0; i < 21; i++)

System.out.print("-");

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值