|
We know that (1) if the whole hundred years, can be divisible by 400 is a leap year; (2) if not the whole hundred year divisible by 4 is a leap year. Every 400 years, there are 97 leap years. In view of this, Java programs can make the following design:
The first step, it is determined whether the year is divisible by 400, it can then, is a leap year. Such as 1600, 2000, 2400 is a leap year.
The second step, the first step is not established on the basis of the judgment whether the year is divisible by 100, if it is, it is not a leap year. Such as 1900, 2100, 2200 is not a leap year.
The third step, the second step is not established on the basis of the judgment whether the year is divisible by 4, if it is, it is a leap year. Such as 1996, 2004, 2008 is a leap year.
The fourth step is not established on the basis of the third step, it is not a leap year. Such as 1997, 2001 and 2002 is not a leap year.
import java.util.Scanner; // into the scanner
public class runnian
{
public static void main (String [] args) // Sting [] args do not forget to write came
{
Scanner s = new Scanner (System.in); // declare variables scanner
System.out.println ( "Please enter the year"); // prompted Year
int nianfen = s.nextInt (); // get the year value of the next line of input
if (nianfen% 400 == 0) {System.out.println (nianfen + "is a leap year");} // determines whether or not divisible by 400
else if (nianfen% 100 == 0) {System.out.println (nianfen + "not a leap year");} // determines whether or not divisible by 100
else if (nianfen% 4 == 0) {System.out.println (nianfen + "is a leap year");} // determines whether or not divisible by four
else {System.out.println (nianfen + "not a leap year");}
}
}
After preliminary testing, this program can correctly determine whether it is a leap year. This procedure If errors and omissions, please treatise. We must realize there are other methods, please reply provided.
=======================
After studying the video in teaching others, wrote the first two kinds of methods to achieve, you can use only one if-else statements. Code is as follows:
import java.util.Scanner;
public class runnian
{
public static void main (String [] args)
{
Scanner s = new Scanner (System.in);
System.out.println ( "Please enter the year");
int nianfen = s.nextInt ();
if (! nianfen% 4 == 0 && nianfen% 100 = 0 || nianfen% 400 == 0) {System.out.println (nianfen + "is a leap year");}
// Year divisible by 4 but not divisible by 100, or can be divisible by 400 years
else {System.out.println (nianfen + "not a leap year");}
}
} |
|
|
|