3条件中的一条if语句
问题描述:
该程序应该检查输入的年份是否为闰年。但编译时我已经遇到了错误。 检查,如果它是一个闰年的计算公式如下:3条件中的一条if语句
If you can divide the year by 4 it's a leap year...
unless you can at the same time also divide it by 100, then it's not a leap year...
unless you can at the same time divide it by 400 then it's a leap year.
public class Schaltjahr {
public static void main (String[] args) {
double d;
String eingabe;
eingabe = JOptionPane.showInputDialog("Gib das Jahr ein "); //Type in the year
d = Double.parseDouble(eingabe);
if ((d % 4 == 0) & (d % 100 == 0) && (d % 400 = 0)) {
JOptionPane.showMessageDialog(null,"Es ist ein Schaltjahr"); //It is a leap year
} else {
if ((d % 4 == 0) & (d % 100 == 0))) {
JOptionPane.showMessageDialog(null, "Es ist kein Schaltjahr"); //It is not a leap year
}
} else {
if (d % 4 == 0) {
JOptionPane.showMessageDialog(null, "Es ist ein Schaltjahr"); // It is a leap year
}
}
}
}
在编译时我收到此错误:
Schaltjahr.java:16: error: illegal start of expression
if ((d % 4 == 0) & (d % 100 == 0))) {
^
Schaltjahr.java:19: error: 'else' without 'if'
} else {
^
2 errors
答
你有两个连续的else
声明,不会编译。
变换:
} else {
if ((d % 4 == 0) & (d % 100 == 0))) {
... INTO ...
} else if ((d % 4 == 0) & (d % 100 == 0))) {
答
为什么不干脆把单一条件:
if ((d % 4 == 0) && (d % 100 != 0) || (d % 400 == 0)) {
JOptionPane.showMessageDialog(null,"Es ist ein Schaltjahr"); //It is a leap year
else
JOptionPane.showMessageDialog(null, "Es ist kein Schaltjahr"); //It is not a leap year
由于今年是一个如果
闰一it divides on 4 AND NOT on 100 OR divides on 400
例子:
2016 - leap (divides on 4 and not on 100)
2000 - leap (divides on 400)
1900 - not leap (divides on 4, but on 100 as well)
2015 - not leap (doesn't divide on 4, doesn't divide on 400)
你甚至可以把它当成
JOptionPane.showMessageDialog(null, ((d % 4 == 0) && (d % 100 != 0) || (d % 400 == 0))
? "Es ist ein Schaltjahr"
: "Es ist kein Schaltjahr");
,但我想这是的可读性。
答
单if语句来检查闰年是: -
if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))
因为我希望你知道什么'else'意思..程序应该如何决定使用哪'else'块? – Tom
而不是写'else {if(...){...}}',写'else if(...){...}'。 – Gendarme
另外,当你指'&&'时,你在几个地方使用'&'。 – Gene