Java基础编程题目——编写一个代表日期的类
编写一个代表日期的类,其中有代表年、月、日的三个属性,创建日期对象时要判断参数提供的年、月、日是否合法,不合法要进行修正。“年”默认值为2000;“月”的值在1到12之间,默认值为1;“日”由一个对应12个月的整型数组给出合法值,特别地,对于2月,通常为28天,但闰年的2月最多29天。闰年是该年的值为400的倍数,或者为4的倍数但不为100的倍数。将创建的日期对象输出时,年月日之间用“/”分隔。.
·
编写一个代表日期的类,其中有代表年、月、日的三个属性,创建日期对象时要判断参数提供的年、月、日是否合法,不合法要进行修正。“年”默认值为2000;“月”的值在1到12之间,默认值为1;“日”由一个对应12个月的整型数组给出合法值,特别地,对于2月,通常为28天,但闰年的2月最多29天。闰年是该年的值为400的倍数,或者为4的倍数但不为100的倍数。将创建的日期对象输出时,年月日之间用“/”分隔。
import java.util.Scanner;
public class dates {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next(); //输入日期 格式为2020/3/21
String[] arr = s.split("/"); // 以/为分隔符,提取年月日
int y = Integer.parseInt(arr[0]); //转换为int型
int m = Integer.parseInt(arr[1]);
int d = Integer.parseInt(arr[2]);
date riqi = new date(y, m, d); //新建日期类
riqi.print(); //打印日期
}
}
class date {
int year = 2000; //初始化日期
int month = 1;
int day = 1;
int[] montha = new int[] {1, 3, 5, 7, 8, 10, 12}; //大月
int k = 0; //判断大小月
public void print() {
System.out.println(year + "/" + month + "/" + day);
}
public date(int year, int month, int day) {
if(year > 0 && year < 3000) { //年份在1-2999
this.year = year;
if(month > 0 && month < 13) //月份在1-12
this.month = month;
for(int i = 0; i < montha.length; i++) //判断是否为大月
if(month == montha[i]) {
k = 1;
break;
}
if(k == 1 && day > 0 && day < 32) //大月
this.day = day;
else if(k == 0 && month != 2 && day > 0 && day < 31) //小月
this.day = day;
else if(year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {
if(day > 0 && day < 30) //闰年2月
this.day = day;
}
else if(day > 0 && day < 29) //平年2月
this.day = day;
}
}
}
更多推荐



所有评论(0)