当前位置:   article > 正文

JAVA判断输入日期是否合法_java输入年月日并判断是否输入正确

java输入年月日并判断是否输入正确
  1. 简单判断输入日期是否合法
    运行结果:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
public class JudgeDate {
	public static boolean judge(int y,int m,int d) {
		boolean p=false;
		if(m<1||m>12) {
			System.out.print("月份不合法");
			p=false;}
		else if(m==1||m==3||m==5||m==7||m==8||m==10||m==12) {
			if(d<=31) {
				p=true;}
			else {
				p=false;
				System.out.print("日期不合法");
			}
			}
		else if(m==2) {
			if(y%400==0||(y%4==0&&y%100!=0)) {
				if(d<=29) {
					p=true;
				}
				else {
					p=false;
					System.out.print("日期不合法");
				}
			}
			else {
				if(d<=28){
					p=true;
				}
				else {
					p=false;
					System.out.print("日期不合法");
				}
			}
		}
		else {
			if(d<=30){
				p=true;
			}
			else {
				p=false;
				System.out.print("日期不合法");
			}
		}
		return p;
	}
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		@SuppressWarnings("resource")
		Scanner s=new Scanner(System.in);
		int y=s.nextInt();
		int m=s.nextInt();
		int d=s.nextInt();
		if(judge(y,m,d)) {
			System.out.print(y+"/"+m+"/"+d);
		}
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  1. 编写一个代表日期的类,其中有代表年、月、日的3个属性,创建日期对象时要判断参数提供的年、月、日是否合法,不合法要进行纠正。“年”默认值为2000;月的值在1到12之间,默认值为1;日由一个对应12个月的整型数组给出合法值,特别地,对于2月,通常为28天,但闰年的2月最多29天,闰年是该年值为400的倍数,或者为4的倍数但不为100的倍数。将创建的日期对象输出时,年月日之间用“/”分隔。

在这里插入图片描述

public class JudgeDate {
	static int year=2000;
	static int month;
	int day;
	public JudgeDate(int y,int m,int d) {
		year=y;
		if(m<1||m>12) {
		month=1;
		}
		else {
			month=m;
		}
		day=checkDay(d);
	}
	public String toString() {
		return year+"/"+month+"/"+day;
	}
	public static int checkDay(int d) {
		int mouthDay[]= {31,28,31,30,31,30,31,31,30,31,30,31};
		if(month==2&&d<=29&&(year%400==0||(year%4==0&&year%100!=0))){
			return d;
			}
		else {
			if(d>mouthDay[month-1]) {
				d=mouthDay[month-1];
			}
		}
		return d;
	}
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		JudgeDate d1=new JudgeDate(2020,01,32);
		System.out.println(d1);
		JudgeDate d2=new JudgeDate(2020,12,24);
		System.out.println(d2);
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/52176
推荐阅读
相关标签
  

闽ICP备14008679号