看见别人用C写了些代码求对称日期:比如今天2011年11月02日,所以自己用java写了一个版本。 (注:有参考他人意见)
package com;
import java.util.Scanner;
public class CalcPalindrome {
/**
* @param args
* autho:Mars Ma
*/
public static final int min_year = 1000;
public static final int max_year = 9999;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("please input year range(1000-9999) eg:2011-2100");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String[] yRange = scanner.next().split("-");
if (Integer.parseInt(yRange[0]) < min_year
|| Integer.parseInt(yRange[0]) > max_year) {
System.out.println("Dear..year range error!Please check");
} else if (Integer.parseInt(yRange[1]) > max_year
|| Integer.parseInt(yRange[1]) < min_year) {
System.out.println("Dear..year range error!Please check");
} else if (Integer.parseInt(yRange[0]) > Integer
.parseInt(yRange[1])) {
System.out
.println("Dear..can you reverse two year's position!");
} else {
CalcPalindromeDates(Integer.parseInt(yRange[0]),
Integer.parseInt(yRange[1]));
}
}
}
private static void CalcPalindromeDates(int minYera, int maxYear) {
// TODO Auto-generated method stub
for (int nYear = minYera; nYear <= maxYear; nYear++) {
String year = String.valueOf(nYear);
String str1 = "";
for (int i = year.length() - 1; i >= 0; i--) {
str1 = str1 + year.charAt(i);
}
String month = str1.substring(0, 2);
String day = str1.substring(2, 4);
if (!validateDate(Integer.parseInt(year), Integer.parseInt(month),
Integer.parseInt(day))) {
continue;
}
System.out.println("Palindrome Date is " + year + month + day);
}
}
private static boolean validateDate(int year, int month, int day) {
// TODO Auto-generated method stub
if (month < 1 || month > 12) {
return false;
}
if (day < 1 || day > 31) {
return false;
}
if ((month == 4 || month == 6 || month == 11) && day == 31) {
return false;
}
if(month == 2){
boolean leap = (year%4 ==0 && (year%100 !=0||year%400==0));
if(day>29||(day == 29 && !leap)){
return false;
}
}
return true;
}
}
结果如下:
please input year range(1000-9999) eg:2011-2100
2011-2100
Palindrome Date is 20111102
Palindrome Date is 20200202
Palindrome Date is 20211202
Palindrome Date is 20300302
Palindrome Date is 20400402
Palindrome Date is 20500502
Palindrome Date is 20600602
Palindrome Date is 20700702
Palindrome Date is 20800802
Palindrome Date is 20900902