如何使用带有嵌套if-else语句的switch语句输出日期

嗨,这是我用于我的应用程序的代码。 但是在某些情况下,在输入数据时会使用if-else语句和嵌套的if-else语句显示不同System.out.print的一个长答案。 我需要做些什么才能显示一个答案? 我希望程序显示输入的日期是否显示其是否为有效日期,输入的日期是否为闰年,如果输入的日期或月份显示错误则显示

package javaapplication18; import java.util.Scanner; /** * * @author Thurston Pietersen */ public class JavaApplication18 { public static void main(String[] args) { int sI,fI ,sL, month, day, year; String mm, dd, yyyy, date; Scanner keyboard = new Scanner(System.in); // TODO code application logic here System.out.print("Input date using the following format mm/dd/yyyy: "); date = keyboard.next(); sL = date.length(); fI = date.indexOf("/"); sI = date.lastIndexOf("/"); mm = date.substring(0,fI); month = Integer.parseInt(mm); dd = date.substring((fI+1),sI); day = Integer.parseInt(dd); yyyy = date.substring((sI+1),sL); year = Integer.parseInt(yyyy); switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (day > 31) System.out.print(date + " is an invalid date."); else System.out.print(date + " is a valid date."); case 4: case 6: case 9: case 11: if (day > 30) System.out.print(date + " is an invalid date."); else System.out.print(date + " is a valid date."); case 2: if (year % 4 == 0) if (day > 29) System.out.print(date + " is an invalid day."); else System.out.print(date + " is a valid date and leap year."); else if (day > 28) System.out.print(date + " is an invalid day."); else System.out.print(date + " is a valid date."); default: System.out.println("The date: " + date + " has an invalid month"); } } } 

在所有情况下你都错过了break 。 因此,开关掉线,并且所有情况都被执行。 在适当的地方插入break

 switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if (day > 31) System.out.print(date + " is an invalid date."); else System.out.print(date + " is a valid date."); break; // Here case 4: case 6: case 9: case 11: if (day > 30) System.out.print(date + " is an invalid date."); else System.out.print(date + " is a valid date."); break; // Here case 2: if (year % 4 == 0) if (day > 29) System.out.print(date + " is an invalid day."); else System.out.print(date + " is a valid date and leap year."); else if (day > 28) System.out.print(date + " is an invalid day."); else System.out.print(date + " is a valid date."); break; // Here default: System.out.println("The date: " + date + " has an invalid month"); } 

请做一个永远封闭你的if s和else s用花括号的habbit。