2016-05-30 118 views
-2

該程序應該檢查輸入的年份是否爲閏年。但編譯時我已經遇到了錯誤。 檢查,如果它是一個閏年的計算公式如下: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 
+2

因爲我希望你知道什麼'else'意思..程序應該如何決定使用哪'else'塊? – Tom

+1

而不是寫'else {if(...){...}}',寫'else if(...){...}'。 – Gendarme

+2

另外,當你指'&&'時,你在幾個地方使用'&'。 – Gene

回答

3

你有兩個連續的else聲明,不會編譯。

變換:

} else { 
     if ((d % 4 == 0) & (d % 100 == 0))) { 

... INTO ...

} else if ((d % 4 == 0) & (d % 100 == 0))) { 
3

爲什麼不乾脆把單一條件

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"); 

,但我想這是的可讀性

0

單if語句來檢查閏年是: -

if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)))