-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeapYear.java
64 lines (56 loc) · 1.37 KB
/
LeapYear.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.javamultiplex.datetime;
import java.util.Scanner;
/**
*
* @author Rohit Agarwal
* @category Date and Time
* @problem Year is leap year or not?
*
*/
public class LeapYear {
/*
* Year is called leap year if.
* 1) It is evenly divisible by 4 and not by 100.
* 2) It is evenly divisible by 400.
*
*/
public static void main(String[] args) {
Scanner input = null;
try {
input = new Scanner(System.in);
System.out.println("Enter year : ");
String year = input.next();
if (isValidYear(year)) {
if (isLeapYear(year)) {
System.out.println("This is leap year.");
} else {
System.out.println("This is not leap year.");
}
} else {
System.out.println("Year should be 4 digit long.");
}
} finally {
if (input != null) {
input.close();
}
}
}
private static boolean isValidYear(String year) {
boolean result = false;
// Regular expression that matches a String contains 4 digits.
String pattern = "[0-9]{4}";
if (year.matches(pattern)) {
result = true;
}
return result;
}
private static boolean isLeapYear(String year) {
boolean result = false;
// Converting String to int.
int myYear = Integer.parseInt(year);
if ((myYear % 4 == 0 && myYear % 100 != 0) || myYear % 400 == 0) {
result = true;
}
return result;
}
}