Determine leap year using Java? [duplicate] - java

This question already has answers here:
Java Code for calculating Leap Year
(22 answers)
Closed 1 year ago.
Here is my requirements. Determine If a Year Is a Leap Year Algorithm:
If the year can be evenly divided by 4, then it is a leap year
Except when the year can be evenly divided by 100, then it is not a leap year
Except when the year can be evenly divided by 400, then it is a leap year
Otherwise, it is not a leap year
I need to know if i did right?
private static boolean isLeapYear(int userInput){
boolean leapYear= false;
if (userInput % 4 == 0 ){
leapYear = true;
if (userInput % 4 == 0 && userInput % 100 ==0) {
leapYear = false;
if(userInput % 400 == 0){
leapYear = true;
}
}
}
else {
leapYear = false;
}
return leapYear;
}

I used this one in C++.
return ((userInput % 400) || ((userInput % 4) && !(userInput % 100)));

Better use this condition for a valid leap year
(((year%4 == 0) && (year%100 !=0)) || (year%400==0))
Here is a similar C program to check leap year.

Correct! Simplified:
Remove year % 4 from 2nd if bc already tested in 1st if
Remove else bc already set leap = False at top
Python:
def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap
1-Line:
def is_leap(year):
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

I used this short method:
private static Boolean isLeapYear(int year) {
return year % 4 == 0 ? (year % 100 == 0 ? ( year % 400 == 0 ? true : false) : true) : false ;
}

year = int(input("Enter year to determine if it is a leap year"))
def leap_year(year):
"""This is a function to determine if a year
is a leap year"""
if year%4==0 and year%100!=0:
print("This is a Leap year")
if year%400==0:
print ("This is a Leap year")
else:
print ("This is not a leap year")
leap_year(year)

From 1700 to 1917, official calendar was the Julian calendar. Since then they we use the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that 32nd day in 1918, was the February 14th.
In both calendar systems, February is the only month with a variable amount of days, it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4 while in the Gregorian calendar, leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
So the program for leap year will be:
def leap_notleap(year):
yr = ''
if year <= 1917:
if year % 4 == 0:
yr = 'leap'
else:
yr = 'not leap'
elif year >= 1919:
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
yr = 'leap'
else:
yr = 'not leap'
else:
yr = 'none actually, since feb had only 14 days'
return yr

With python and another languages, you can use the property that if you substract 1 day to march, you have the last day of february. If is leap year, that day is 29.
from datetime import datetime, timedelta
def is_leap_year(year: int):
marzo = datetime(year, 3, 1)
febrero = marzo - timedelta(1)
if febrero.day == 29:
return True
else:
return False

Every year that is exactly divisible by four is a leap year, except
for years that are exactly divisible by 100, but these centurial years
are leap years if they are exactly divisible by 400. For example, the
years 1700, 1800, and 1900 are not leap years, but the years 1600 and
2000 are.[2]
— United States Naval Observatory
Source: https://en.wikipedia.org/wiki/Gregorian_calendar
Thus, for a year to qualify as a leap year, it should be:
Either divisible by 400 -OR-
Divisible for 4 but not by 100
Use this fact in your code as follows:
if((userInput % 400 == 0) || (userInput % 4 == 0 && userInput % 100 != 0)) {
System.out.println(userInput + " is a leap year");
}
For production code, I recommend you use the OOTB java.time API:
if (java.time.Year.isLeap(userInput)) {
System.out.println(userInput + " is a leap year");
}
Learn more about the modern date-time API from Trail: Date Time.

userInput % 4 == 0 && userInput % 100 ==0 is equivalent to userInput % 400 == 0
and userInput % 4 == 0 then it is definitely Leap year so need not to check any other condition.

Related

I am using Boolean variables to print the number of days in a calendar days. The outputs aren't what I am expecting

I am trying to write a program which shows the number of days in a given month of a year. The outputs for the month of February, non leap years (no output) and the months having 30 days in leap years is incorrect (output is 29). How could I resolve this?
public class Q11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner number1 = new Scanner(System.in);
Scanner number2 = new Scanner(System.in);
System.out.println("Enter the month (1-12)");
int month = number1.nextInt();
System.out.println("Enter the year");
int year = number2.nextInt();
int number_of_days = 0;
boolean N1 = (month == 1) ||
(month == 3) ||
(month == 5) ||
(month == 7) ||
(month == 8) ||
(month == 10) ||
(month == 12);
boolean N2 = (month == 2) && (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
boolean N3 = (month == 2) && (year % 400 <= 1) || (year % 4 <= 1) && (year % 100 == 0);
boolean N4 = (month == 4) ||
(month == 6) ||
(month == 9) ||
(month == 11);
if (N1)
System.out.println(". This month has 31 days");
else if (N2)
System.out.println(". This month has 29 days");
else if (N3)
System.out.println(". This month has 28 days");
else if (N4)
System.out.println(". This month has 30 days");
}
}
Problem
You run into a problem due to the fact how the program evaluates your boolean expressions. Remember the rules for boolean precedence. && is evaluated first and takes precedence. Also, the formula is evaluated from left to right. Operator precedence can be overruled with the correct setting of parentheses.
E.g. if you have a && b || c, a && b is evaluated first, after which we evaluate its result against || c. But: a && (b || c) is evaluated by first evaluating b || c and then evaluating this result against && a.
In your case, when you enter e.g. month = 4 and year = 2020 the following happens:
The rule n1 is skipped - month is not listed.
The rule n2 is evaluated - month is not equals to two and the year is not divisible by 400; so far everything goes to plan. But now - the next || comes around to bite you. The year is divisible by 4 AND it is not divisible by 100. The program now incorrectly prints 29.
The rules n3 and n4 are solved like n2 and are left as an exercise for the reader :)
Solution
Easiest way is to understand why n2 is failing and optimize the formula. Since this is a homework task I don't want to solve it for you.
General
One scanner instance on System.in is enough.
Your variable names should follow the Java naming convention, lowerCaseCamelCase instead of snake_case and N1.
Parting thought
Try using a switch statement on month - it will make your code a bit easier to understand. Finally: Good luck in your studies.
In your existing code make the following changes.
this checks for leap year.
if it is divisible by 4 and not a century year, its is a leap year
or if is divisible by 400 it is a leap year.
otherwise, it isn't.
boolean N2 = (year %4 == 0 && year %100 != 0) || (year % 400 == 0);
Now just use the negation of the boolean to test for non leap year.
if (N1)
System.out.println(". This month has 31 days");
else if (N4) {
System.out.println(". This month has 30 days");
} else if (month == 2) {
boolean N2 = (year %4 == 0 && year %100 != 0) || (year % 400 == 0);
if (N2) {
System.out.println("This month has 29 days");
} else {// must not be leap year.
System.out.println("This month has 28 days");
}
} else {
System.out.printf("Bad month(%d) entered", month);
}
Also, you should only use one Scanner for all console input.
An alternative approach
In case you didn't know, the enhanced switch statement introduced in Java 13 would be perfect for this.
it takes multiple cases
and returns an argument for processing.
public class Q11 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the month (1-12)");
int month = scanner.nextInt();
System.out.println("Enter the year");
int year = scanner.nextInt();
boolean isLeapYear = (year %4 == 0 && year %100 != 0) || (year % 400 == 0);
String proclamation = switch(month) {
case 1,3,5,7,8,10,12 -> "This month has 31 days.";
case 4,6,9,11 -> "This month has 30 days";
case 2 -> "This month has %d days".formatted(isLeapYear ? 29 : 28);
default -> "Bad month (%d) entered.".formatted(month);
};
System.out.println(proclamation);
}
}

Math problem in java trying to figure out whats wrong with my code [duplicate]

This question already has answers here:
Java Code for calculating Leap Year
(22 answers)
Closed 3 years ago.
so the code works but some years which should be leap years are not like 2008 is showing its not a leap year which it was.
//is leap year if...
if ((whichYear % 4 == 0) && (whichYear % 100 == 0) && (whichYear % 400 == 0))
{
isLeapYear = true;
daysLeftInYear = 366;
System.out.println("true " + daysLeftInYear);
}
else
{
isLeapYear = false;
daysLeftInYear = 365;
System.out.println("false " + daysLeftInYear);
}
The easiest way is to just break it down into two possibilities.
If (year % 100 == 0) {
// if century year
} else {
// if not century year.
}
The rest is up to you.
Well of course it won't work with 2008 :) Because you defined leap years as being divisible by 4 AND divisible by 100 AND divisible by 400 :) With this definition only every 400th year will be a leap year, for example 1600.
The correct definition of a leap year is: Divisible by 4 AND if it is divisible by 100, then also divisible by 400. For example 1700 is not a leap year, but 1200 is.
So in terms of Java this would lead to:
int year; // initialize it with some year
boolean leapYear = year % 4 == 0 && ((year % 100 == 0) == (year % 400 == 0))

How to check if a number if divisible by two different values?

I've only just started college, and one of the first things we're learning is Java. I'm currently learning about if statements. For one of my homework assignments, I need to write a program that asks for the user to input a year. Then, the program needs to determine whether that year is a leap year or not.
The question states that if the year is divisible by 4, it is a leap year. Also, if the year is divisible by 100, it should also be divisible by 400 in order to be a leap year.
This is what I've written so far:
System.out.print("Type a year: ");
int year = Integer.parseInt(reader.nextLine());
if (year % 4 == 0 || year % 100 == 0 && year % 400 == 0) {
System.out.print("The year is a leap year.");
} else {
System.out.print("The year is not a leap year.");
}
I'm expecting the program to check if the year is divisible by 4, or if the year is divisible by both 100 and 400.
Right now, when I enter the year 1800, the output says the year is a leap year, but I'm expecting it to say it is not a leap year. I suspect this is because the if statement is true when one of the conditions is true, which is the case because 1800 is divisible by 4. However, I can't seem to find out the right way to do it. Help would be much appreciated.
Your expression is asking "Is year a multiple of four or is it a multiple of 100 and also a multiple of 400?" The second half is entirely redundant because any multiple of both 100 and 400 was already a multiple of 4 in the first place (same with 400 and 100 also) and the result is clearly more inclusive than you intended.
Remember that a series of AND'd conditions will restrict the scenarios that match while ORs will broaden it. So start with finding multiples of four and then refine that a bit by adding in the secondary condition about multiples of 100.
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) /* right! */
Since A(B+C) is equivalent to AB+AC in Boolean logic you could also expand this and it might read more clearly to you:
(year % 4 == 0 && year % 100 != 0) || (year % 4 == 0 year % 400 == 0) /* expanded */
The parentheses aren't really necessary but I left them for clarity.
Another perspective that might help you think about this is reversing the condition to find the years that aren't leap years. It's very similar in structure to the one you attempted so I think that studying it might give you some insight where your thought process went wrong:
year % != 0 || (year % 100 == 0 && year % 400 != 0) /* NON-leap years */
Finally, one last thing to point out is that it only takes either side of an OR to be true for the whole expression to be true. Looking back at your original logic, once the program has determined that year % 4 == 0 is true the rest of it is extra work that doesn't need to be performed. The program will actually skip those steps and this concept is called short-circuiting.
Another way to word the leap year criteria is this: if the year is divisible by 4 but not by 100, or it is divisible by 400, it is a leap year.
It's the "but not by 100" part that is not expressed in your code.
Example 1 (your fixed code):
System.out.print("Type a year: ");
int year = Integer.parseInt(reader.nextLine());
if (year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0) {
System.out.print("The year is a leap year.");
} else {
System.out.print("The year is not a leap year.");
}
Example 2 (other if for better understand)
System.out.print("Type a year: ");
int year = Integer.parseInt(reader.nextLine());
boolean isLeap = false;
if(year % 100 == 0){
if(year % 400 == 0)
isLeap = true;
} else if (year % 4 == 0){
isLeap = true;
}
System.out.print(isLeap ? "The year is a leap year." : "The year is not a leap year.");
Since any number divisible by 400 or 100 would, obviously, be divisible by 4. We would need to add additional check to make sure the year is a leap year
class Scratch {
public static void main(String[] args) {
for (int i = 1800; i <= 2000; i++) {
if (i % 4 == 0) {
if ((i % 100 == 0 && i % 400 == 0) || (i % 100 != 0)) {
System.out.println(i + ": A leap Year");
} else {
System.out.println(i + ": Not a leap year");
}
} else {
System.out.println(i + ": Not a leap year");
}
}
}
}

Java leap year code problems

import java.util.Scanner;
public class Hw2JamesVaughn {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
if((year < 1582) == (year % 4==0))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
if((year > 1582) == (year % 100 != 0) || (year % 400 == 0))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
This is the assignment.
(To determine if a particular year is a leap year, use the following logic:
the year must be divisible by 4
starting from 1582, if the year is divisible by 100, it must also be divisible by 400
Thus, the year 1700 is not a leap year, but 2000 is. However, 1500 is leap year since it was
before 1582, the adoption year of Gregorian calendar.
Your program will ask for a year, and then display whether the year is leap year or not.)
I have gotten this far with my java leap year program but its not working! Ive been working on this and i have no idea what is wrong.
Firstly, this if((year < 1582) == (year % 4==0)) checks boolean equality. I think you wanted an if((year < 1582) && (year % 4==0)) but I'm afraid that still doesn't fix your logic.
I suggest you start by creating a method. The first part should test if the year is less then 1582. If so, return true if it's a multiple of 4. The second part is well described on Wikipedia here. Putting it together gives something like,
private static boolean isLeapYear(int year) {
if (year < 1582) {
return (year % 4 == 0);
}
/*
* Rest of algorithm from: http://en.wikipedia.org/wiki/Leap_year
*/
if (year % 4 != 0) {
/*
* if (year is not divisible by 4) then (it is a common year)
*/
return false;
} else if (year % 100 != 0) {
/*
* else if (year is not divisible by 100) then (it is a leap year)
*/
return true;
}
/*
* else if (year is not divisible by 400) then (it is a common year)
* else (it is a leap year)
*/
return (year % 400 == 0);
}
Then you can use printf to output the result,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = input.nextInt();
System.out.printf("%d %s leap year", year, isLeapYear(year) ? "is a"
: "is not a");
}
Finally, your original code could be implemented like -
if (year < 1582 && year % 4 == 0)
System.out.println(year + " is a leap year");
else if (year < 1582)
System.out.println(year + " is not a leap year");
else if (year >= 1582 && (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)))
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
Apart from the algorithm you can calculate leap year using java's built in Calendar api.
static boolean isLeapYear(int year){
Calendar calendar= Calendar.getInstance();
calendar.set(Calendar.YEAR,year);
return calendar.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}

Represent a leap year using boolean expressions [duplicate]

This question already has answers here:
Java Code for calculating Leap Year
(22 answers)
Closed 8 years ago.
Question from exam:
Write a Boolean expression for the following:
A is a leap year.
Any help would be appreciated!
A year is a leap year if it is divisible by 4 and not divisible by 100, but it is always one if it is divisible by 400. You can translate this to code literally:
int year = 2004;
boolean leap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
The modulo operator (%) gives you the remainder when dividing the numbers, so it is equal to 0 if the first number is divisible by the second.
As Bathsheba points out, this only works for the Gregorian Calendar (our modern system since 1582 in some countries or even later in others), if you want to handle years prior to this date, the code would be much more complicated and it would require some research for the exact rules at that time. In an exam, however, you should not need to worry about those.
http://en.wikipedia.org/wiki/Leap_year
from article pseudo code:
if year is not divisible by 4 then common year
else if year is not divisible by 100 then leap year
else if year is not divisible by 400 then common year
else leap year
if((A%4==0) && A%100!=0)||A%400==0)
You can use this boolean function to determine a leap year:
public static boolean IsLeapYear(int year)
{
if ((year % 4) == 0)
{
if ((year % 100) == 0)
{
if ((year % 400) == 0)
return true;
else
return false;
}
else
return true;
}
return false;
}
This follows the two rules to determine a leap year
First Rule: The year divisible by 4 is a leap year.
Second Rule: If the year is divisible by 100, then it is not a leap year. But If the year is divisible by 400, then it is a leap year.

Categories

Resources