C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Later Date Program - Java Program

Write a program in Java to accept day number (between 1 and 366) and year (yyyy) from the user and display the corresponding date. Also accept ‘N’ from the user where (1 ≤ N ≤ 100) to compute and display the future date ‘N’ days after the given date.

Display error message if the value of the day number or ‘N’ are not within the limit. Day number is calculated taking 1st January of the given year as 1.

Test your program with given set of data and some random data.

Example 1
INPUT:
DAY NUMBER: 50
YEAR: 2024
N = 25
OUTPUT:
ENTERED DATE: FEBRUARY 19, 2024
25 DAYS LATER: MARCH 15, 2024

 

Example 2
INPUT:
DAY NUMBER: 321
YEAR: 2024
N: 77
OUTPUT:
ENTERED DATE: NOVEMBER 16, 2024
77 DAYS LATER: FEBRUARY 1, 2025

 

Example 3
INPUT:
DAY NUMBER: 400
YEAR: 2024
N: 125
OUTPUT:
INCORRECT DAY NUMBER
INCORRECT VALUE OF ‘N’

 

import java.util.Scanner; class LaterDate{ public static void main(String[] args){ Scanner in = new Scanner(System.in); boolean validDayNum = true; boolean validN = true; System.out.print("DAY NUMBER: "); int dayNum = Integer.parseInt(in.nextLine()); System.out.print("YEAR: "); int year = Integer.parseInt(in.nextLine()); System.out.print("N: "); int n = Integer.parseInt(in.nextLine()); if(dayNum < 1 || (dayNum > 365 && !isLeap(year))){ validDayNum = false; System.out.println("INCORRECT DAY NUMBER"); } else if(dayNum > 366 && isLeap(year)){ validDayNum = false; System.out.println("INCORRECT DAY NUMBER"); } if(n < 1 || n > 100){ validN = false; System.out.println("INCORRECT VALUE OF 'N'"); } if(!validDayNum || !validN) return; int day[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; String month[] = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"}; if(isLeap(year)) day[1] = 29; int index = 0; while(dayNum > day[index]){ dayNum -= day[index++]; if(index == 12){ index = 0; year++; if(isLeap(year)) day[1] = 29; else day[1] = 28; } } System.out.println("ENTERED DATE: " + month[index] + " " + dayNum + ", " + year); System.out.print(n + " DAYS LATER: "); while(n > 0){ dayNum++; n--; if(dayNum > day[index]){ dayNum = 1; index++; if(index == 12){ index = 0; year++; if(isLeap(year)) day[1] = 29; else day[1] = 28; } } } System.out.println(month[index] + " " + dayNum + ", " + year); } public static boolean isLeap(int y){ if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) return true; return false; } }

Output

 
OUTPUT 1:
DAY NUMBER: 50
YEAR: 2024
N: 25
ENTERED DATE: FEBRUARY 19, 2024
25 DAYS LATER: MARCH 15, 2024

OUTPUT 2:
DAY NUMBER: 321
YEAR: 2024
N: 77
ENTERED DATE: NOVEMBER 16, 2024
77 DAYS LATER: FEBRUARY 1, 2025

OUTPUT 3:
DAY NUMBER: 400
YEAR: 2024
N: 125
INCORRECT DAY NUMBER
INCORRECT VALUE OF 'N'