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

博主利用 正则表达式+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,3,5,7,8,10,12};
		int small[] = {4,6,9,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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值