题目:
某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
要求:
- 确保每个输入的日期都是合法的
- 假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉
- 每行给出 1 个人的姓名(由不超过 5 个英文字母组成的字符串)
- 按 yyyy/mm/dd(即年/月/日)格式给出的生日
- 在一行中顺序输出有效生日的个数、最年长人和最年轻人的姓名,其间以空格分隔。
解题思路:
将输入的时间转为时间毫秒值进行排序和过滤.
import java.text.SimpleDateFormat;
import java.util.*;
/**
目前只拿到15分 ,第三测评点格式错误,第四测评点超时,第三测评的初步想法为时间格式的错误,第四测评点超时未想到!!!!
**/
public class Main {
private static SimpleDateFormat dateformat;
private static final long TODAY_TIME_MILLS = 1410019199000l; //当前时间值为2014-09-06 23:59:59的毫秒值
private static long OLD_TIME_MILLS = -4901500800000l; //1814-09-06 00:00:00 的毫秒值
private static long birthday;
/**
* 人物生日的毫秒值
* @param stTime
* @return
*/
public static long birthdayMills(String stTime){
// stTime=stTime.replaceAll("-","/");
dateformat = new SimpleDateFormat("yyyy/MM/dd"); //时间格式
try {
birthday = dateformat.parse(stTime).getTime();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
return birthday;
}
/**
* 判断时间长度
* @param stTime
* @return
*/
public static boolean booleanStTime(String stTime) {
if (stTime.length()!=10){
return true;
}
return false;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String nextLine = scanner.nextLine();//人数;
Integer integer = Integer.valueOf(nextLine); //要测试的人数
int count = 0 ; // 统计合格的人员
String maxName = ""; //最大值人员
Long maxDate = OLD_TIME_MILLS; //求最大值生日
String minName = ""; //最小值人员
Long minDate = TODAY_TIME_MILLS; //求最小值生日
String[] strings = new String[2];
//输入测试人员的信息
for (int i = 0; i < integer; i++) {
String s = scanner.nextLine();
strings = s.split(" ");
if(booleanStTime(strings[1]))continue; //当名字有空格时,导致时间不对,计算时间长度
//计算生日人员的毫秒值
long birth = birthdayMills(strings[1]);
int strLength = strings[0].length(); //名字长度不能超过5
if (birth>TODAY_TIME_MILLS||birth<OLD_TIME_MILLS||strLength>5)continue; //比较毫秒值的正确性
count++;
if (birth>maxDate){
maxDate = birth;
maxName = strings[0];
}
if (birth<minDate){
minDate = birth;
minName = strings[0];
}
}
scanner.close();
System.out.print(count+" "+minName+" "+maxName);
}
}