2020年8月8日Java学习日记

学习内容:

 1、日期类

定义一个日期类Date,私有数据成员有:int型变量year, month, day。公有函数成员有:

三个形参均有默认值的构造函数,年月日的默认值依次为1000,1,1;

int isleap()判断year是否为闰年,若是返回1,否则返回0;

int check()判断日期是否合法,若合法返回1,否则返回0;

void setdate()设置year,month,day的值;

void display()按 “年-月-日”的格式输出日期,判断是否合法,若不合法输出Error Date,若合法,输出是否是闰年的信息;

复制代码
复制代码
 1 import java.util.Scanner;
 2 public class Date1 {
 3     private int year,month,day;
 4     Date1(int y,int m,int d){
 5         year=y;
 6         month=m;
 7         day=d;
 8     }
 9     Date1(){
10         year=1000;
11         month=1;
12         day=1;
13     }
14     public int isleap() {
15         if((year%4==0&&year%100!=0)||year%400==0)
16             return 1;
17         else 
18             return 0;
19     }
20     public int check() {
21         if((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&day<=31)return 1;
22         else if((month==4||month==6||month==9||month==11)&&day<=30)return 1;
23         else if(isleap()==1)
24             {if(month==2&&day<=29)return 1;
25         else return 0;}
26         else  if(isleap()==0)
27         {if(month==2&&day<=28)return 1;
28         else return 0;}
29         else return 0;  
30     }
31     public void setdate() {
32         Scanner con=new Scanner(System.in);
33         System.out.println("请输入年、月、日:");
34         year=con.nextInt();
35         month=con.nextInt();
36         day=con.nextInt();
37     }
38     public void display() {
39         System.out.println(year+"-"+month+"-"+day);
40         if(check()==0)System.out.println("Error Date!");
41         if(check()==1)
42             {if(isleap()==1)System.out.println("闰年!");
43              else System.out.println("平年!");}
44     }
45     public static void main(String[] args) {
46         Date1[] d=new Date1[3];
47         d[0]=new Date1();
48         d[1]=new Date1(2020,5,20);
49         d[2]=new Date1();
50         d[2].setdate();
51         for(int i=0;i<3;i++) {
52             d[i].display();
53         }
54     }
55 }
复制代码
复制代码

  

原文地址:https://www.cnblogs.com/9635741zly/p/14176356.html