目前,我正在编写一个程序,要求用户输入日,月,年。然后程序检查日期是否有效。但是,对于2月份,当输入是闰年时,我无法输出正确的响应。
import javax.swing.*;
public class ValidDate{
public static void main(String[]args){
int day,month,year;
day = Integer.parseInt(JOptionPane.showInputDialog("Enter a day"));
month = Integer.parseInt(JOptionPane.showInputDialog("Enter a month"));
year = Integer.parseInt(JOptionPane.showInputDialog("Enter a year"));
switch(month){ //this statement will check whether or not the days are valid
case 1:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
break;
case 2:
if ( day >= 1 && day <= 28 || month % 4 == 0 && day >= 1 && day <= 29 ){ //look at
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 3:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 4:
if ( day >= 1 && day <= 30 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 5:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 6:
if ( day >= 1 && day <= 30 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 7:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 8:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 9:
if ( day >= 1 && day <= 30 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 10:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 11:
if ( day >= 1 && day <= 30 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}
case 12:
if ( day >= 1 && day <= 31 ){
System.out.println("Date is valid");
}
else{
System.out.println("Date is not valid");
}//case ended
}
}
}
输入闰年时得到的输出是
Date is not valid
Date is valid
Date is valid
Date is valid
Date is valid
Date is valid
Date is valid
答案 0 :(得分:0)
没有
中断;
声明,一旦找到了合适的案例,它就会落空并执行下一个案例。除非您要创建批量案例,否则请添加break语句 我的意思是批量案例:
enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
public boolean isWorkDay() {
switch(this) {
case SATURDAY:
case SUNDAY:
return false;
default:
return true;
}
}
}
答案 1 :(得分:0)
变化:
month % 4 == 0
为:
year % 4 == 0
如果您正在尝试将其用于学习目的。否则,您可以使用以下方法验证闰年:
GregorianCalendar gc = new GregorianCalendar();
if (gc.isLeapYear(year))