博主利用 正则表达式+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;
}