小强在统计一个小区里居民的出生年月,但是发现大家填写的生日格式不统一,例如有的人写 199808,有的人只写 9808。有强迫症的小强请你写个程序,把所有人的出生年月都整理成 年年年年-月月 格式。对于那些只写了年份后两位的信息,我们默认小于 22 都是 20 开头的,其他都是 19 开头的。
输入格式:
输入在一行中给出一个出生年月,为一个 6 位或者 4 位数,题目保证是 1000 年 1 月到 2021 年 12 月之间的合法年月。
输出格式:
在一行中按标准格式 年年年年-月月 将输入的信息整理输出。
输入样例 1:
9808
输出样例 1:
1998-08
输入样例 2:
0510
输出样例 2:
2005-10
输入样例 3:
196711
输出样例 3:
1967-11
解题思路
问题分解:
- 大家填写的生日格式不统一,需要根据要求(把所有人的出生年月整理为年年年年-月月)更换为标准格式。
- 当出生年月为6位数时改为年年年年-月月,当为4位数时判断年年小于22的话就补上20开头,其余是19开头。
解题过程中遇到的问题
暂无
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取输入的年月
String input = scanner.next();
// 调用函数处理并输出结果
System.out.println(standardizeBirthMonth(input));
}
private static String standardizeBirthMonth(String input) {
String year, month;
if (input.length() == 6) {
// 如果输入为6位数,直接提取年和月
year = input.substring(0, 4);
month = input.substring(4, 6);
} else {
// 如果输入为4位数,根据年份前两位判断世纪
int yearPrefix = Integer.parseInt(input.substring(0, 2));
year = (yearPrefix < 22 ? "20" : "19") + input.substring(0, 2);
month = input.substring(2, 4);
}
return year + "-" + month;
}
}