优化这段代码 System.out.printf("请输入年份"); int year = input.nextInt(); if (year>0){ System.out.printf("请输入月份"); int month = input.nextInt(); if (month >= 1 && month <= 12){ System.out.printf("请输入天数"); int day = input.nextInt(); int days =0; if (month == 2){ if (year%4==0 && year%100 !=0 || year%400==0){ days = 29; }else { days = 28; } } else if (month == 4 | month == 6 | month == 9 | month == 11) { days = 30; } else if (month == 1 | month == 3 | month == 5 | month == 7 | month == 8 | month == 10| month == 12){ days = 31; }else { System.out.printf("天数输入错误"); } if(day >= 1 && day <= days) { System.out.println(year + "-" + month + "-" + day); }else { System.out.printf("天数输入错误"); } }else { System.out.printf("月份输入错误"); } }else { System.out.printf("年份输入错误"); }
时间: 2023-03-31 11:02:47 浏览: 94
输入年月,判断年份及季节、月份天数
到12){ System.out.printf("请输入日期"); int day = input.nextInt(); if (day >= 1 && day <= 31){ System.out.printf("%d年%d月%d日", year, month, day); }else{ System.out.printf("日期输入有误"); } }else{ System.out.printf("月份输入有误"); } }else{ System.out.printf("年份输入有误"); }
可以将输入年份、月份、日期的部分提取出来,写成一个方法,减少重复代码。同时,可以加入异常处理,避免用户输入非法字符导致程序崩溃。代码如下:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = getYear(input);
int month = getMonth(input);
int day = getDay(input);
System.out.printf("%d年%d月%d日", year, month, day);
}
public static int getYear(Scanner input) {
int year = ;
while (true) {
try {
System.out.printf("请输入年份");
year = input.nextInt();
if (year > ) {
break;
} else {
System.out.printf("年份输入有误");
}
} catch (InputMismatchException e) {
System.out.printf("年份输入有误");
input.next();
}
}
return year;
}
public static int getMonth(Scanner input) {
int month = ;
while (true) {
try {
System.out.printf("请输入月份");
month = input.nextInt();
if (month >= 1 && month <= 12) {
break;
} else {
System.out.printf("月份输入有误");
}
} catch (InputMismatchException e) {
System.out.printf("月份输入有误");
input.next();
}
}
return month;
}
public static int getDay(Scanner input) {
int day = ;
while (true) {
try {
System.out.printf("请输入日期");
day = input.nextInt();
if (day >= 1 && day <= 31) {
break;
} else {
System.out.printf("日期输入有误");
}
} catch (InputMismatchException e) {
System.out.printf("日期输入有误");
input.next();
}
}
return day;
}
阅读全文