例001 判断某一年是否为闰年

来源:互联网 发布:小猪o2o源码下载 编辑:程序博客网 时间:2024/05/19 14:52
import java.util.Scanner;public class LeapYear {public static void main(String[] args) {// TODO Auto-generated method stubScanner scan = new Scanner(System.in);System.out.println("请输入一个年份:");long year = scan.nextLong();if(year % 4 ==0 && year % 100 != 0 || year % 400 == 0)System.out.println(year + "是闰年!");elseSystem.out.println(year + "不是闰年!");}}
关键语句是:
year % 4 ==0 && year % 100 != 0 || year % 400 == 0
扩展:
判断从2000年1月1日到2016年5月1日一共经历多少天。(代码自己原创)
public class Days {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] LeapYear = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] NonLeapYear = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int i, d, year, s = 0;


for(year = 2000; year < 2016; year++)
{
if(year % 4 ==0 && year % 100 != 0 || year % 400 == 0)
d = 366;
else
d = 365;


s += d;
}


if(year % 4 ==0 && year % 100 != 0 || year % 400 == 0)
{
for(i = 0; i <= 3; i++)
s += LeapYear[i];
}
else
{
for(i = 0; i <= 3; i++)
s += NonLeapYear[i];
}


s += 1;


System.out.println("2000年1月1日到2016年5月1日一共经历了" + s + "天");


}
}
用数组存储平年和闰年的月的天数是因为当题目的日期改了,还可以通过数组来计算,不用人工去算。编程就是要让计算机做这些计算的事情。
我不知道这段代码的最终结果是否正确,结果是2000年1月1日到2016年5月1日一共经历了5966天。
原创粉丝点击