Hi, I'm new to Java. I've been working on this question, wrote the code and checked the results with some examples and it seems to be doing fine. I would be glad if any of the teachers can check the code for me.
Also, please do let me know if there's a more efficient way for writing the code.
Many thanks!
Question :
Write a Java program that replies either Leap Year or Not a Leap Year, when a year is given as keyboard input.
(i) A Year is a Leap Year if the year can be divided by 4 but not by 100
(eg: 1976).
(ii) A year that can be divided by both 4 and 100 is Leap Year if it can also
be divided by 400.
My code :
package exams;
import java.util.*;
public class Exams {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int p, q, r, s;
System.out.print("Enter Year");
p = input.nextInt();
if(p%4==0){
if(p%100==0){
if(p%400==0){
System.out.println("Leap Year");
}
}
else if(p%100!=0){
System.out.println("Not a Leap Year");
}
}
}
}
1 answer
System.out.print("Enter Year");
year = input.nextInt();
boolean leap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year % 400 == 0)
leap = true;
else
leap = false;
}
else
leap = true;
}
else
leap = false;
if(leap)
System.out.println(year + " is a leap year.");
else
System.out.println(year + " is not a leap year.");