为了使我的代码更加美观和简短,我尝试从以下内容更改我的代码:
do
{
System.out.print("Enter day: ");
day = input.nextInt();
if ((isLeapYear && month == 2 && (day < 1 || day > 29)) ||
(!isLeapYear && month == 2 && (day < 1 || day > 28)) ||
((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)) ||
((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month ==12) && (day < 1 || day > 30)))
{
System.out.println("Invalid input");
}
}
while ((isLeapYear && month == 2 && (day < 1 || day > 29)) ||
(!isLeapYear && month == 2 && (day < 1 || day > 28)) ||
((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)) ||
((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month ==12) && (day < 1 || day > 30)));
对此:
boolean invalidDay = (isLeapYear && month == 2 && (day < 1 || day > 29)) ||
(!isLeapYear && month == 2 && (day < 1 || day > 28)) ||
((month == 4 || month == 6 || month == 9 || month == 11) && (day < 1 || day > 30)) ||
((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
month == 10 || month ==12) && (day < 1 || day > 30));
do
{
System.out.print("Enter day: ");
day = input.nextInt();
if (invalidDay)
{
System.out.println("Invalid input");
}
}
while (invalidDay);
第二种方法没有按预期工作,但第一种方法效果很好。我唯一改变的是将长布尔表达式放入单个布尔变量中。谢谢。