{
System.out.println("Please enter the date you would like to split");
System.out.println("Please make sure it is in the format DDMMYYYY");
date = sc.nextInt();
day = date / 1000000;
month = (date / 10000) - (day * 100);
year = date - (date / 10000) * (10000);
switch(day)
{
case 1: case 21: case 31:
suffix = "st";
break;
case 2: case 22:
suffix = "nd";
break;
case 3: case 23:
suffix = "rd";
break;
case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 24: case 25: case 26: case 27: case 28: case 29: case 30:
suffix = "th";
break;
default:
System.out.println("Error, Please enter a valid day (i.e. DD) that is between 01 - 31");
break;
}
switch(month)
{
case 4: case 6: case 9: case 11:
if ((day < 1) || (day > 30))
{
System.out.println("Error this day does not exist");
}
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if ((day < 1) || (day > 31))
{
System.out.println("Error this day does not exist");
}
break;
case 2:
if ((day < 1) || (day > 28))
{
if ((day != 29))
{
System.out.println("Error this day does not exist");
}
else if ((year % 4 != 0) || ((year % 400 != 0) && (year % 100 == 0)))
{
System.out.println("Error this day does not exist");
}
//If it isn't a leap year, febuary cannot have 29 days
}
break;
default:
System.out.println("Error this day does not exist");
}
switch(month)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "Febuary";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
default:
System.out.println("Error, Please make sure the month (i.e. MM) is between 01 and 12");
break;
}
if ((day == 29) && (month == 2))
{
System.out.println("It is the 29th day of Febuary in " + year + ".");
}
else
{
System.out.println("It is the " + day + suffix + " day of " + monthName + " in " + year + ".");
}
}
所以基本上,当我运行此程序并输入70702020时,我将获得所有这些输出“错误,请输入介于01-31之间的有效日期(即DD)”“今天没有错误”“错误,请确保月份(即MM)在01到12之间”然后它将输出最终输出(仅当用户输入有效日期时才打算使用此输出)
您正在使用开关而不是if(blah blah)语句。意思是说,该陈述是正确的,现在会产生错误。您的代码说您的输入没有问题。您的后缀仍然会打印,但是我会打印空引号,因为它是一个空字符串。我建议在使用开关之前检查输入。或使用“ System.exit(1)”,如果输入错误,系统将退出该系统。
编辑:同样,根据您的计算,您的工作日将等于“ 70”,从而导致其他错误。
break
仅打破switch语句switch语句中的break
命令只能从switch语句中退出,不是整个方法。
您有一系列三个switch语句。
顺便说一句,通过现代的java.time类解析为文本要简单得多。 try {
LocalDate ld =
LocalDate
.parse(
"70702020" ,
DateTimeFormatter.ofPattern( "ddMMuuuu" )
)
;
} catch ( DateTimeParseException e ) {
…
}
无效的输入抛出DateTimeParseException
。