问题提出
编写程序,输入年份,打印出该年的年历(12个月的),效果如下图所示。
一点提示
使用 Java 自带的 Calendar 类得到一个 Calendar 类对象,然后我们可以去得到每个月的第一天是星期几
Calendar 类不能直接 new 得到对象,需要使用 getInstance() 函数
1 2 |
//得到一个Calendar对象 Calendar c = Calendar.getInstance(); |
Calendar 类的 set 可以设置自己想要的日期为当前日期
get(Calendar.DAY_OF_WEEK) 可以得到某一天是星期几,由于其内部默认为美国时区,所以我们设置月份和计算星期几要减一
1 2 3 4 |
//设置日期为当前月份的第一天,由于时区的原因,month-1,get(java.util.Calendar.DAY_OF_WEEK) - 1 c.set(year, month - 1 , 1 ); //求出第一天是星期几 int FirstDayInWeek = c.get(Calendar.DAY_OF_WEEK) - 1 ; |
然后通过循环打印出每个月的日历,注意大小月和闰月问题。
源码分享
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
//导入相关包 import java.util.Scanner; import java.util.Calendar;
public class MyCalendar { public static void main(String[] args) { //保存用户输入的年份 int year; //保存每个月的天数 int days = 0 ; //保存月份 String[] months;
months = new String[ 13 ]; months[ 1 ] = "January" ; months[ 2 ] = "February" ; months[ 3 ] = "March" ; months[ 4 ] = "April" ; months[ 5 ] = "May" ; months[ 6 ] = "June" ; months[ 7 ] = "July" ; months[ 8 ] = "August" ; months[ 9 ] = "September" ; months[ 10 ] = "October" ; months[ 11 ] = "November" ; months[ 12 ] = "December" ;
//接受用户输入的年份 Scanner in = new Scanner(System.in); System.out.print( "Please input years:" ); year = in.nextInt();
//得到一个Calendar对象 Calendar c = Calendar.getInstance();
//循环 12 个月 for ( int month = 1 ; month <= 12 ; month++) { //标题 System.out.println( "\n Month's name is " + months[month]); for ( int i = 1 ; i <= 27 ; i++) System.out.print( "=" ); System.out.println( "\nSun\tMon\tTue\tWed\tThu\tFri\tSat" );
// 判断当前月份的天数 if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { days = 31 ; } if (month == 4 || month == 6 || month == 9 || month == 11 ) { days = 30 ; } if (month == 2 ) { //闰年判断 if (((year % 4 == 0 ) && (year % 100 != 0 )) || (year % 400 == 0 )) { days = 29 ; } else { days = 28 ; } }
//设置日期为当前月份的第一天,由于时区的原因,month-1,get(java.util.Calendar.DAY_OF_WEEK) - 1 c.set(year, month - 1 , 1 ); //求出第一天是星期几 int FirstDayInWeek = c.get(Calendar.DAY_OF_WEEK) - 1 ;
//用来控制换行 int cnt = 0 ;
//前面的空位 for ( int j = 0 ; j < FirstDayInWeek; j++) { System.out.print( " " ); cnt++; }
//打印当前月份日历 for ( int i = 1 ; i <= days; i++) { if (cnt == 7 ) { System.out.printf( "\n" ); cnt = 0 ; } System.out.printf( "%-4d" , i); cnt++; }
System.out.print( "\n" ); } } } |
到此这篇关于利用Java编写一个属于自己的日历的文章就介绍到这了,更多相关Java日历内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/weixin_62511863/article/details/124706453
查看更多关于利用Java编写一个属于自己的日历的详细内容...