项目实战:判断闰年平年并输出某月的天数

1.项目案例

所谓闰年,就是指 2 月有 29 天的那一年。闰年同时满足以下条件:

1.年份能被 4 整除。
2.年份若是 100 的整数倍,须被 400 整除,否则是平年。

例如,1900 年能被 4 整除,但是因为其是 100 的整数倍,却不能被 400 整除,所以是平年;而 2000 年就是闰年;1904 年和 2004 年、2008 年等直接能被 4 整除且不能被 100 整除,都是闰年;2014 是平年。

下面根据上面的知识点编写一个判断闰年的案例,其主要功能如下:

1.判断用户输入的年份是不是闰年。
2.根据年份和月份输出某年某月的天数。

2.项目实现

(1)新建一个类并在类中导入java.util.Scanner类,并且创建一个类的入口main(),及具体实现如下:

import java.util.Scanner;
public class plan04{
	public static void main(String[] args){
	...;
	}
}

(2)在main中编写代码,获取用户键入年份和月份,具体实现如下:

System.out.print("Enter the year: ");
	int year = sc.nextInt();
	System.out.print("Enter the month: ");
	int month = sc.nextInt();

(3)根据用户输入的年份判断是平年还是闰年,具体实现如下:

if((year%4==0)&&(year%100!=0))||(year%400==0){
	days[1] = 28;
	System.out.println(year+" is runnian,"+month+" have  "+days[month-1]+" tian");
}
else{
	System.out.println(year+" is pingnian,"+month+" have  "+days[month-1]+" tian");
}

3.项目效果

Enter the year: 2012
Enter the month: 2
2012 is runnian,2 have  29 tian
Enter the year: 2014
Enter the month: 2
2014 is pingnian,2 have  28 tian
posted @ 2021-03-12 11:17  Biile  阅读(418)  评论(0编辑  收藏  举报