TurkuBasicOOPinJava / Week 2: Methods, strings and lists /9. Leap years, part 2 (two-part exercise)
KaiquanMah's picture
Create 9. Leap years, part 2 (two-part exercise)
f2e8436 verified
raw
history blame
2.77 kB
1. First, write the method
public static boolean isLeapYear(int year)
...which returns true or false depending on whether the given year is a leap year or not.
A year is a leap year if it is evenly divisible by four.
However, a year divided by 100 is a leap year only if it is also divided by 400.
So, for example, 2000 and 2004 are leap years, but 1900 is not.
2. After that, write the method
public static void leapYears()
...which asks the user to enter the start and end of the year.
The method then prints all leap years found between these years.
Make use of the method isLeapYear!
Example on method execution:
Give start: 1970
Give end: 1977
1972 is a leap year
1976 is a leap year
import java.util.Random;
import java.util.Scanner;
public class Test{
public static void main(String[] args){
final Random r = new Random();
leapYears();
}
// ADDED 1
public static boolean isLeapYear(int year){
if (year % 4 == 0) {
// divided by 100
if (year % 100 == 0) {
// divided by 400
if (year % 400 == 0) {
return true;
}
return false;
}
// normal leap year, divided by 4
else {
return true;
}
}
// not a leap year
return false;
}
// ADDED 2
public static void leapYears() {
Scanner reader= new Scanner(System.in);
System.out.print("Give start: ");
int start = Integer.valueOf(reader.nextLine());
System.out.print("Give end: ");
int end = Integer.valueOf(reader.nextLine());
for (int i = start; i <= end; i++) {
if (isLeapYear(i)) {
System.out.println(i + " is a leap year");
}
}
}
}
Testing method isLeapYear...
Testing with parameter 1984
Is a leap year: true
Testing with parameter 1985
Is a leap year: false
Testing with parameter 1900
Is a leap year: false
Testing with parameter 2000
Is a leap year: true
Testing with parameter 2004
Is a leap year: true
Testing with parameter 2003
Is a leap year: false
Testing method leapYears...
Testing with input 1970, 1990
Give start: 1970
Give end: 1990
1972 is a leap year
1976 is a leap year
1980 is a leap year
1984 is a leap year
1988 is a leap year
Testing with input 1780, 1801
Give start: 1780
Give end: 1801
1780 is a leap year
1784 is a leap year
1788 is a leap year
1792 is a leap year
1796 is a leap year
Testing with input 2001, 2015
Give start: 2001
Give end: 2015
2004 is a leap year
2008 is a leap year
2012 is a leap year
Testing with input 1897, 1905
Give start: 1897
Give end: 1905
1904 is a leap year