Question
Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user to generate and display the corresponding date. Also, accept N (1 <= N <= 100) from the user to compute and display the future date corresponding to āNā days after the generated date. Display an error message if the value of the day number, year and N are not within the limit or not according to the condition specified.
Test your program with the following data and some random data:
Example 1:
INPUT:
DAY NUMBER: 255
YEAR: 2018
DATE AFTER (N DAYS): 22
OUTPUT:
DATE: 12TH SEPTEMBER, 2018
DATE AFTER 22 DAYS: 4TH OCTOBER, 2018
Example 2:
INPUT:
DAY NUMBER: 360
YEAR: 2018
DATE AFTER (N DAYS): 45
OUTPUT:
DATE: 26TH DECEMBER, 2018
DATE AFTER 45 DAYS: 9TH FEBRUARY, 2019
Example 3:
INPUT:
DAY NUMBER: 500
YEAR: 2018
DATE AFTER (N DAYS): 33
OUTPUT:
DAY NUMBER OUT OF RANGE
Example 4:
INPUT:
DAY NUMBER: 150
YEAR: 2018
DATE AFTER (N DAYS): 330
OUTPUT:
DATE AFTER (N DAYS) OUT OF RANGE
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class Date
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int n, day, year, i, p, k=0;
int ar[]={0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
String month[]={"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
System.out.print("Day number");
day = sc.nextInt();
System.out.print("Year");
year =sc.nextInt();
System.out.print("N: ");
n = sc.nextInt();
p = day + n;
int a = 1, b = 1, date = 0, nday = 0, year1 = year;
if(year % 4 == 0)
{
/* if leap year then add 1 to 'arr' from february to december else arr remains unchanged*/
for(i = 2; i <= 12; i++)
{
ar[i] += 1;
}
}
/* if day>=1 and day<=ar[12] then we find the date else show an error*/
if(day >= 1 && day <= ar[12])
{
for(i = 0; i <= 12; i++)
{
if(ar[i] < day)
{
a = i;
}
if(ar[i] > day)
{
break;
}
}
date = day - ar[a];
}
else
{
k = 1;
}
if(k == 1)
{
System.out.println("Days are out of Range");
}
/* checking if n>=1 and n<=100 .if true, then we start incrementing date else show an error*/
else if(k != 1 && n >= 1 && n <= 100)
{
/*we are checking whether 'p' which is equal to day+n is greater than 365 if non-leap year or 366 if leap-year*/
/*if true then increment by one else do not increment year by 1*/
if(p > ar[12])
{
p = p - ar[12];
year1 = year1 + 1;
}
/*incremented day is found here*/
for(i = 0; i <= 12; i++)
{
if(ar[i] < p)
{
b = i;
}
if(ar[i] > p)
{
break;
}
}
nday = p - ar[b];
}
else
{
k = 1;
System.out.println("N Days are out of range ");
}
if(k != 1)
{
System.out.println("Date is : " + date + "th " + month[a + 1] + " " + year);
System.out.println("N Date is : "+ nday + "th " + month[b + 1] + " " + year1);
}
}
}