首页 > 编程知识 正文

年月计算月份,根据年份和月份计算天数

时间:2023-05-03 05:27:13 阅读:248382 作者:146

一、判断闰年并输出(2000年---3000年)每14个换一行

如下代码:

public class Test000 {public static void main(String[] args) {int count=0;int countAll=0;for(int i=2000;i<=3000;i++){if(checkYear(i)==0){System.out.print(i+" ");count++;countAll++;}if(count!=0 && count%14==0){System.out.println();//换行count=0;//清零}}System.out.println();System.out.println("2000-3000年之间一共有"+countAll+"个闰年!");}public static int checkYear(int year){return ((year%4==0 && year%400!=0)||(year%400==0)) ? 0 : -1;//闰年返回0,否则返回-1}}二、输入年份和月份,判断并输出该年该月的具体天数

如下代码:

import java.util.Scanner;public class Test001 {public static void main(String[] args) {Scanner scan=new Scanner(System.in);System.out.println("请输入年份(例如:2014)");int year=scan.nextInt();System.out.println("请输入月份(例如:6)");int month=scan.nextInt();int days;boolean flag=false;switch(month){case 4:case 6:case 9:case 11:days=30;break;case 2:if((year%4==0 && year%100!=0)||(year%400==0)){days=29;flag=true;}else{days=28;}break;default :days=31;}if(flag){System.out.println(year+"年是闰年");}else{System.out.println(year+"不年是闰年");}System.out.println(year+"年"+month+"月有"+days+"天");}}闰年包含两个条件:

若年份为整百数,则除以400,没有余数就是闰年-------------year%400==0
若年份不是整百数,则除以4,没有余数就是闰年--------------year%4==0 && year%100!=0


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。