Java Leap Year Calculator [duplicate] - java

This question already has an answer here:
Why is my leap year algorithm not working (Java)? [duplicate]
(1 answer)
Closed 8 years ago.
I am making a scanner object to get a year and test to see if it is a leap year. Just want some feedback. Is this right what I have? Thank you!
import java.util.Scanner;
public class Micro4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int testDate = input.nextInt();
boolean divFour = (((testDate % 4) == 0));
boolean divHundred = (((testDate % 100) != 0));
boolean divFourHundred = (((testDate % 400) != 0));
if (divFour && divHundred && divFourHundred) {
System.out.println(testDate + " is a leap year.");
} else {
System.out.println(testDate + " is not a leap year.");
}
}
}

The logic is slightly wrong. 2000 is a leap year, yet it isn't according to your program. The proper logic should've been:
if ((divFour && divHundred)||!divFourHundred) {
Also, as Dave Galvin suggested, do use better variable names to improve readability.

The trick is to put this into code:
A year is a leap year if it is divisible by 4, but century years are
not leap years unless they are divisible by 400.
I am checking if a (year is a multiple of 4 AND not a multiple of 100) OR (year is multiple of 400).
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
System.out.println("Leap");
else
System.out.println("Not leap.");

Related

finding next leap year java

The code works when the first year is a leap year so if I said the year was 2004 it would return 2008, but when the starting year is not a leap year, it returns nothing. How would I output that if, for ex: the given year was 2001, 2002, or 2003, the next leap year would be 2004. I know the while loop makes sense but I don't know what to put inside it. ALSO I can only use basic java formatting so no inputted classes like java.time.Year
public static boolean leapYear(int year) {
boolean isLeap = true;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
isLeap = true;
else
isLeap = false;
} else
isLeap = true;
} else {
isLeap = false;
}
return isLeap;
}
public static int nextLeapYear(int year) {
int nextLeap = 0;
if (leapYear(year)) {
nextLeap = nextLeap + 4;
} else {
while (!leapYear(year)) {
nextLeap++;
}
nextLeap += 1;
}
year += nextLeap;
return year;
}
Granted this doesn't take much processing. But if you want to increase the efficiency of your program you might consider the following:
All leap years must be divisible by 4. But not all years divisible by 4 are leap years. So first, check for not divisible by 4. That will be 75% of the cases. In that event, return false.
if (year % 4 != 0) {
return false;
}
As you continue, the year must be divisible by 4 so just make certain it is not a century year. This will be evaluated 25% of the time and will return true 24% of the time.
if (year % 100 != 0) {
return true;
}
lastly, the only category not checked are years divided by 400. If we got here in the logic, then it must be a century year. So return accordingly. This will evaluate to true .25% of the time.
return year % 400 == 0;
Your code is broken in multiple ways:
You say: If the given year is a leap year, then the next leap year will be 4 years later. This is false. If you pass in 1896, your algorithm returns 1900, but this is wrong; whilst 1896 is a leap year, 1900 is not.
Your isLeapYear code would be miles easier to read if you early-exit. That method should have a lot of return statements and fall less indentation.
Your while loop will keep asking the same question over and over, and if you ask the same question to a stable method (and your isLeapYear method is stable), you get the same answer, resulting in an infinite loop. Presumably, you don't want while(!leapYear(year)), you want while(!leapYear(year + nextLeap)), and you don't want to increment nextLeap once more after the while loop.
in fact, your edge case of: If the stated year is already a year, add 4 - is not necessary at all. Think about it: You can just eliminate that if/else part. Your code will just be nextLeap, that while loop, and a return statement. a 3-liner, if you do right.
EDIT: I figured it out yay!
for anybody struggling w/ this, this is what worked for me :)
public static boolean leapYear(int year) {
if(year % 4 == 0)
{
if( year % 100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year % 400 == 0)
return true;
else
return false;
}
else
return true;
}
else
return false;
}
public static int nextLeapYear (int year) {
int nextLeap = 0;
while(leapYear(year + nextLeap) == false){
nextLeap++;
}
if(leapYear(year) == true)
nextLeap += 4;
year += nextLeap;
return year;
}
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.
- United States Naval Observatory
You can greatly simplify the function, leapYear as shown below:
public static boolean leapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
Demo:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(leapYear(1999));
System.out.println(leapYear(2000));
System.out.println(leapYear(1900));
System.out.println(leapYear(1904));
}
public static boolean leapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}
Output:
false
true
false
true
Then, you can use it in the function, nextLeapYear as shown below:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(nextLeapYear(1999));
System.out.println(nextLeapYear(2000));
System.out.println(nextLeapYear(2001));
}
public static int nextLeapYear(int year) {
// If year is already a leap year, return year + 4
if (leapYear(year)) {
return year + 4;
}
// Otherwise, keep incrementing year by one until you find a leap year
while (!leapYear(year)) {
year++;
}
return year;
}
public static boolean leapYear(int year) {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
}
Output:
2000
2004
2004
In production code, you should use the OOTB (Out-Of-The-Box) class, java.time.Year to deal with a year.
import java.time.Year;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(nextLeapYear(1999));
System.out.println(nextLeapYear(2000));
System.out.println(nextLeapYear(2001));
}
public static int nextLeapYear(int year) {
Year yr = Year.of(year);
// If year is already a leap year, return year + 4
if (yr.isLeap()) {
return yr.plusYears(4).getValue();
}
// Otherwise, keep incrementing year by one until you find a leap year
while (!yr.isLeap()) {
yr = yr.plusYears(1);
}
return yr.getValue();
}
}
Output:
2000
2004
2004
Learn more about the modern date-time API at Trail: Date Time.
It seems it not easy to get nextLeapYear() 100 % correct. Allow me to suggest a simpler way of thinking about it that will also — so I believe — make it simpler to code correctly and/or fix any bug there may be.
Declare a variable candidateLeapYear to hold a year that we don’t yet know whether will be the next leap year after year. Initialize it to year + 1 since we know that the next leap year will need to be strictly greater than year. In a loop test whether candidateLeapYear is a leap year (use the other method), and as long as it isn’t, increment by 1. When the loop terminates, candidateLeapYear holds the next leap year. Return it.

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

Leap Year Program [duplicate]

This question already has answers here:
Java Code for calculating Leap Year
(22 answers)
Closed 5 years ago.
import java.util.*;
public class LeapYear
{
public static void main (String[]args)
{
Scanner scan= new Scanner (System.in);
System.out.println("Please enter in the year");
int year=scan.nextInt();
if (year % 4 ==0)
{
{
if (year % 100 ==0);
else
System.out.println("The year,"+year+",is a leap year!");
}
if(year % 400==0)
System.out.println("The year, "+year+",is a leap year!");
}
else
System.out.println("The year, "+year+",is not a leap year!");
}
}
Hey everyone! Above is my code for a leap year program- It seems to work well, except whenever I enter a number such as 3000 or 300, the JVM just stops and shuts the terminal window. Could someone please guide as to why it's not accepting these numbers (Also, please forgive me that my code is not formatted properly- I'm new and trying to do the best I can)
NOTE: It is displaying all the right answers when I test 1900, 1996, 2004, 164, and 204 as years. It will simply not accept 300 or 3000.
Thanks Again!
check the following lines:
if (year % 100 ==0);
else
300 % 100 == 0, nothing is output.
You asked that we forgive your formatting, but it is your formatting that is leading you to miss the problem. Especially when you are first starting out, you will find it most helpful to understand what's going on if you are extremely diligent in your formatting. Suggestion: always include the braces, even when they are optional, and always provide the 'else' portion of every 'if' statement. Thus:
if (condition) {
action;
} else {
alternative action;
}
In your case, you will see in your lines 11 and 12 where you have syntacticly correct code, but very likely not what you meant. The opening brace on line 11 seems out of place and the semicolon at the end of line 12 is simply taking the place of the "action" that would take place if that condition were true.
if ((year % 4) == 0) {
// could be a leap year
if ((year % 100) == 0) {
// could be a leap year too
if ((year % 400) == 0) {
println("yes, this is a leap year ... divisible by 4, 100, AND 400");
} else {
// not a leap year ... divisible by 4 and 100, but NOT 400
}
} else {
println("yes, this is a leap year ... it's divisible by 4 but not 100");
}
} else {
// absolutely not a leap year
}
You can make your code more concise if you do this instead:
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
System.out.println("The year,"+year+",is a leap year!");
} else {
System.out.println("The year, "+year+",is not a leap year!");
}
Also, notice that this formula for calculating leap years only works for years after "1583".

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