This program reads a year and tells the user if it's a leap year or not. It uses boolean operators instead of if statements, which would also be a perfectly fine solution.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// LeapYear.java - Tells whether a give year is leap year or not.
// Michael Maus, 22 Sept 2004
import javax.swing.*;
public class LeapYear {
//===================================================================== main
public static void main(String[] args) {
//... Variables
String yearStr; // String version of year before conversion to int.
int year; // year
String leapResult; // Tell's whether it's a leap year or not.
//... Input
yearStr = JOptionPane.showInputDialog(null, "Enter a year.");
year = Integer.parseInt(yearStr);
//... Computation and output
if (isLeapYear(year)) {
leapResult = " is a leap year";
} else {
leapResult = year + " isn't a leap year";
}
//... Output
JOptionPane.showMessageDialog(null, leapResult);
System.exit(0); // Stop GUI program
}
//=============================================================== isLeapYear
static boolean isLeapYear(int yr) {
return (yr%400 == 0) || ((yr%4 == 0) && (yr%100 != 0));
}
}
|