I am trying to find the next leap year. I have the first leap year. What and where should I code? I know I need a print statement somewhere stating "is the leap year next to ("the previous leap year.)" Just not sure how to go about. for example,
input: 2016
output: 2016 is a leap year.
2020 is the leap year next to 2016.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int inputYear;
int nextLeapYear;
boolean isLeapYear;
isLeapYear = false;
inputYear = scnr.nextInt();
if (inputYear % 4 == 0) {
if (inputYear % 100 == 0) {
isLeapYear = inputYear % 400 == 0;
} else {
isLeapYear = true;
}
}
if (isLeapYear) {
System.out.println(inputYear + " is a leap year.");
} else {
System.out.println(inputYear + " is not a leap year.");
}
}}
Convert your year into an instance of Year
or use the static Year.isLeap(x)
method. You can then do all of the following:
isLeap
isLeap
do { year = year.plusYears(4); } while (!year.isLeap());
to find the next leap year from a known leap yearjava.time
provides high quality libraries for time-arithmatic, which is otherwise insanely hard to get right due to the intricacies of civil time (DST, leap years, leap seconds).
if (isLeapYear) {
nextLeapYear = inputYear + 4 ;
System.out.println(inputYear + " is a leap year.");
System.out.println(nextLeapYear + " is next leap year.");
}
else {
nextLeapYear = inputYear + inputYear%4 ;
System.out.println(inputYear + " is not a leap year.");
System.out.println(nextLeapYear + " is next leap year.");
}
You can use java.time.Year .
int givenYear = 2016;
int nextLeapYear = givenYear;
if (Year.isLeap(givenYear)) {
while (!Year.isLeap(++nextLeapYear));
System.out.println("Is leap year.");
System.out.println("Next one is: " + nextLeapYear);
}
else {
System.out.println("Not a leap year.");
}
You can also use LocalDate to find the LeapYear 1 :
LocalDate year2016 = LocalDate.ofYearDay(2016, 1);
System.out.println ( "Is 2016 the leap year : " + year2016.isLeapYear());
LocalDate nextLeapYearTest = year2016.plusYears(1);
while(!nextLeapYearTest.isLeapYear()) {
nextLeapYearTest = nextLeapYearTest.plusYears(1);
}
System.out.println ( "The next leapYear is : " + nextLeapYearTest.getYear());
If you love nested ifs and a hardcoded code.
public static boolean isLeapYear(int year) {
if (year > 0 && year <= 9999) {
if(year %4 == 0){
if(year %100 == 0){
if(year % 400 == 0){
return true;
}
return false;
}
return true;
}
}
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.