Java实现日历编写

Java用循环控制语句实现日历

java语言实现日历编写

主要使用了java语言,采用简单的循环语句实现,在学习过程中,掌握了三种循环语句的使用方式。主要学会循环语句的嵌套和分支语句的使用。

package 基本语句;
import java.io.*;
public class Calendar {
	static int year;
	static int weekDay;

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("请输入年份:");
		InputStreamReader ir = new InputStreamReader(System.in);
		BufferedReader in = new BufferedReader(ir);
		String s = in.readLine();
		year = Integer.parseInt(s);
		if(year <1) {
			System.out.println("输入的年份不能小于1!");
			return;
		}
		weekDay = (int)firstDayOfYear(year);
		System.out.println("                     "+year+"年");
		System.out.println("====================================================");
		for (int i = 1;i <=12;i++) {
			System.out.println();
			printMonth(i);
			System.out.println();
		}
		System.out.println("====================================================");
	}
	public static void printMonth(int m) {
		printHead(m);
		int days = daysOfMonth(m);
		for(int i = 1;i<=days;i++) {
			if(i<10)System.out.print("     "+i);
			else System.out.print("    "+i);
			weekDay = (weekDay+1)%7;
			if (weekDay == 0) {
				System.out.println();
				System.out.print("      ");
			}
		}
	}
	public static int daysOfMonth(int m) {
		switch(m) {
			case 1:
			case 3:
			case 5:
			case 7:
			case 8:
			case 10:
			case 12:
				return 31;
			case 4:
			case 6:
			case 9:
			case 11:
				return 30;
			case 2:
				if (isLeapYear(year)) return 29;
				else return 28;
			}
			return 0;
	}
	public static void printHead(int m) {
		System.out.println("   "+m+"月    日    一    二    三    四    五    六");
		System.out.print("      ");
		for (int i = 0;i <weekDay;i++)System.out.print("      ");
	}
	public static long firstDayOfYear(int y) {
		long n;
		n = y*365;
		for (int i =1;i <y;i++){
			if (isLeapYear(i)) n+=1;	
		}
		return n%7;
	}
	public static boolean isLeapYear(int y) {
		
		return ((y%4 ==0 && y%100 != 0)||y%400 ==0);
	
	}

}

运行结果显示

比如显示2019年的日历
在这里插入图片描述
在这里插入图片描述
其他不用剪贴,比较简单,直接看代码即可。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Changcc_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值