加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式_Java_SE_C++_简单题_判断输入的日期是否是正确的

发布时间:2020-12-14 00:57:25 所属栏目:百科 来源:网络整理
导读:博主利用 正则表达式+java语言+逻辑判断 写了一个判断输入的日期是否是正确的小程序, 程序逻辑比较复杂,博主写了好久。。。 import java.util.Arrays;import java.util.Scanner;public class Stringmatch {public static void main(String[] args) {Scanne

博主利用 正则表达式+java语言+逻辑判断 写了一个判断输入的日期是否是正确的小程序,

程序逻辑比较复杂,博主写了好久。。。


import java.util.Arrays;
import java.util.Scanner;

public class Stringmatch {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);

		String k = null;
		boolean correct = false;
		do {
			if (!correct && k != null)
				System.out.println("input incorrect");

			System.out.println("please input the day you born");
			k = s.next();
			k.trim();
			if (!k.matches("[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"))
				continue;
			String[] strings = k.split("-");
			int year = Integer.parseInt(strings[0]);
			int month = Integer.parseInt(strings[1]);
			int day = Integer.parseInt(strings[2]);

			int[] bigmonth = { 1,3,5,7,8,10,12 };
			int[] smallmonth = { 4,6,9,11 };
			if (year < 1900) // 必须是1900年之后出生的
				continue;
			if (month > 12 || month == 0)
				continue;
			if (day == 0)
				continue;

			// 一个月31天的情况
			if (Arrays.binarySearch(bigmonth,month) >= 0) {
				if (day > 31)
					continue;
			}
			// 一个月30天的情况
			else if (Arrays.binarySearch(smallmonth,month) >= 0) {
				if (day > 30)
					continue;
			}
			// 闰年的条件: 1、能整除4且不能整除100 2、能整除400
			// 闰年2月份的情况
			else if (month == 2 && (year % 4 == 0 && year % 100 != 0)
					|| year % 400 == 0) {
				if (day > 29) {
					continue;
				}
			}
			// 平年2月的情况
			else {
				if (day > 28)
					continue;
			}

			correct = true;
		} while (!correct);
		System.out.println("input correctly");
	}
}




C++版本

#include <cstdio>
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;

#pragma warning(disable:4996)

int main()
{
	int month,day;
	while(scanf("%d%d",&month,&day)){
		int big[] = {1,12};
		int small[] = {4,11};
		list<int> bigmonth;
		list<int> smallmonth;
		for(int i=0; i<(sizeof(big)/sizeof(int)); i++)
			bigmonth.push_back(big[i]);
		for(int i=0; i<(sizeof(small)/sizeof(int)); i++)
			smallmonth.push_back(small[i]);
		/*
		for(list<int>::iterator i = bigmonth.begin();i!=bigmonth.end(); ++i)
			cout<<*i<<endl;
		*/

		if(binary_search(bigmonth.begin(),bigmonth.end(),month))
		{
			if(day>31)
				continue;
		}
		else if(binary_search(smallmonth.begin(),smallmonth.end(),month))
		{
			if(day>30)
				continue;
		}
		else if(2 == month){
			if(day>29)
				continue;
		}
		printf("正确的日期");
		break;
	}
	
	return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读