优化这段代码 public class test02 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("年份"); int year = input.nextInt(); System.out.print("月份"); int month = input.nextInt(); if (year>0) { int days; if (month >= 1 && month <= 12) { 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 { days = 31; } System.out.println(+year + "年" + month+"月有" + days + "天"); } else { System.out.println("输入不合法"); } }else { System.out.println("不合法"); } } }
时间: 2023-03-31 08:02:45 浏览: 121
Java输入流Scanner/BufferedReader使用方法示例
这段代码可以进行如下优化:
public class test02 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("年份");
int year = input.nextInt();
System.out.print("月份");
int month = input.nextInt();
int days = ;
if (year > && month >= 1 && month <= 12) {
switch (month) {
case 2:
if ((year % 4 == && year % 100 != ) || year % 400 == ) {
days = 29;
} else {
days = 28;
}
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
break;
}
System.out.println(year + "年" + month + "月有" + days + "天");
} else {
System.out.println("输入的年份或月份不合法");
}
}
}
这里使用了 switch 语句来判断每个月的天数,并且增加了对输入年份和月份的合法性判断。
阅读全文