我的程序读取表示日期的3个整数和表示天数的第4个整数,并计算天数之后的日期。
我正在使用blueJ,我不明白为什么输出的日期不起作用 - 闰年不起作用,唯一可行的情况并且当我进入32日时无效33等我哪里错了?顺便说一句,我们不允许使用任何其他东西,除非是和/或布尔/开关。
我复制了我直接从blueJ写的代码:
import java.util.Scanner;
public class Dates
{
public static void main (String[]args)
{
int day, month, year, num;
int daysInMonth = 0;
final int JAN = 1;
final int FEB = 2;
final int MAR = 3;
final int APR = 4;
final int MAY = 5;
final int JUN = 6;
final int JUL = 7;
final int AUG = 8;
final int SEP = 9;
final int OCT = 10;
final int NOV = 11;
final int DEC = 12;
final int LeapYear = 29;
final int NotLeapYear = 28;
final int MinMonthsInYear = 1;
final int MaxMonthsInYear = 12;
Scanner scan = new Scanner(System.in);
System.out.println("This program reads 3 integers representing a date and a fourth " +
"integer representing amount of days, and calculates the date " +
"after the amount of days.");
System.out.println("Please enter 3 integers- the day, the month and the year");
day = scan.nextInt();
month = scan.nextInt();
year = scan.nextInt();
switch (daysInMonth)
{
case JAN:
case MAR:
case MAY:
case JUL:
case AUG:
case OCT:
case DEC:
daysInMonth=31;
break;
case APR:
case JUN:
case SEP:
case NOV:
daysInMonth=30;
break;
case FEB:
if((year%400)==0 || (year%4)==0 && (year%100)!=0)
{
daysInMonth=LeapYear;
}
else
{
daysInMonth=NotLeapYear;
}
break;
default:
System.out.println("The original date " +day + "/" +month + "/" +year + " is invalid.");
return;
}
if (month<1 && month>12 || year<0)
{
System.out.println("The original date " +day + "/" +month + "/" +year + " is invalid.");
return;
}
System.out.println("Please enter an integer which represents the number of days");
num = scan.nextInt();
if (num<1 && num>10 && num<=0)
{
System.out.println("The number of days must be between 1-10");
return;
}
System.out.println("The original date is " +day + "/" +month + "/" +year + ".");
if (JAN>31 || MAR>31 || MAY>31 || JUL>31 || AUG>31 || OCT>31 | DEC>31)
{
month++;
}
if (APR>30 || JUN>30 || SEP>30 || NOV>30)
{
month++;
}
if (DEC>31)
{
year++;
}
System.out.println("After num days the date is " + day + "/" + month + "/" + year + ".");
}
}
答案 0 :(得分:1)
就像@ MikeJRamsey56所说,你的if语句中有bug。还有一些其他问题,例如daysInMonth
始终为0
。我不想单独为你打电话,因为如果你自己找到它们你会更好地理解它们,但这里有一些要记住的要点:
||
表示“或”,如“如果OR b为真” - 只有当双方都为假时才会跳过 &&
表示“and”,如“如果AND b为真” - 除非双方都为真,否则将跳过。// if the number of days is more than the current month, move on to the next month
。这可以帮助您发现代码中的位置,而这实际上并不是您在if
语句中放置的内容。JAN>31
- JAN
之类的内容是常量(final
),因此值始终为1
。换句话说,该表达式相当于1>31
,它总是错误的。&
和|
(不要与&&
和||
混淆)bitwise-operators;没有太多细节,他们不是你通常想要使用的运营商。如果您在代码中使用它们并且您不打算按位操作,那么结果将是错误的/破坏的。a || b && c || d
? rules实际上是指定的,但仍然容易让自己迷惑。根据经验法则,将多个条件分组到括号中是个好主意,这样您的意图就更清晰了,例如: a || (b && (c || d))
。我希望这足以开始!