0% found this document useful (0 votes)
21 views14 pages

Future Date Calculator in Java

The document describes an algorithm to calculate the date that is N days in the future from a given date. It accepts the starting date and an offset N as input from the user. It then uses helper functions like getMonthName() and isLeapYear() to calculate the future date by iterating through each month and adjusting for years. The algorithm is implemented in a Java program that includes validation checks and outputs the original and future dates. Helper functions are used to retrieve month names and check for leap years.

Uploaded by

FAISAL GHEYAS
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views14 pages

Future Date Calculator in Java

The document describes an algorithm to calculate the date that is N days in the future from a given date. It accepts the starting date and an offset N as input from the user. It then uses helper functions like getMonthName() and isLeapYear() to calculate the future date by iterating through each month and adjusting for years. The algorithm is implemented in a Java program that includes validation checks and outputs the original and future dates. Helper functions are used to retrieve month names and check for leap years.

Uploaded by

FAISAL GHEYAS
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1)

Algorithm:
1. Accept Input:

 Create a Scanner object to read input from the user.

 Prompt the user to enter the day number (between 1 and 366).

 Read and store the entered day number.

 Prompt the user to enter the year (in yyyy format).

 Read and store the entered year.

 Check if the entered day number is within the valid range (1 to 366). If not,
terminate the program.

2. Accept N:

 Prompt the user to enter the offset 'N' (1 <= N <= 100).

 Read and store the entered value of 'N'.

 Check if the entered value of 'N' is within the valid range (1 to 100). If not, terminate
the program.

3. Calculate Future Date:

 Create an array daysInMonth to store the number of days in each month


(considering a leap year).

 Call the isLeapYear function to check if the entered year is a leap year and update
the days in February accordingly.

 Validate the entered day number.

 Initialize variables for the current month, future day number, future month, and
future year.

 Use a loop to find the month and day corresponding to the entered day number.

 Display the entered date using the getMonthName function.

 Calculate the future day number by adding 'N' to the entered day number.

 Adjust the future date if it goes beyond the current year.

 Display the future date using the getMonthName function.


4. Helper Functions:

 getMonthName: Takes a month number as input and returns the corresponding


month name.

 isLeapYear: Takes a year as input and returns true if it is a leap year, false
otherwise.

5. Close Scanner:

 Close the Scanner object to prevent resource leaks.

Program Code:
import [Link];

public class FutureDateCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Accept day number

[Link]("Enter day number (between 1 and 366): ");

int dayNumber = [Link]();

// Accept year

[Link]("Enter year (yyyy): ");

int year = [Link]();

// Check if day number is within the limit

if (dayNumber < 1 || dayNumber > 366) {

[Link]("Incorrect day number. Program terminated.");

return;
}

// Accept N

[Link]("Enter N (1 <= N <= 100): ");

int N = [Link]();

// Check if N is within the limit

if (N < 1 || N > 100) {

[Link]("Incorrect value of 'N'. Program terminated.");

return;

// Calculate the future date

calculateFutureDate(dayNumber, year, N);

// Close the scanner

[Link]();

private static void calculateFutureDate(int dayNumber, int year, int N) {

// Array to store the number of days in each month

int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// Check for a leap year

if (isLeapYear(year)) {
daysInMonth[2] = 29;

// Validate the day number

if (dayNumber > 0 && dayNumber <= 366) {

int month = 1;

// Find the month and day corresponding to the day number

while (dayNumber > daysInMonth[month]) {

dayNumber -= daysInMonth[month];

month++;

// Display the entered date

[Link]("Entered date: %s %d, %d\n", getMonthName(month), dayNumber, year);

// Calculate the future date

int futureDayNumber = dayNumber + N;

int futureMonth = month;

int futureYear = year;

// Adjust the future date if it goes beyond the current year

while (futureDayNumber > daysInMonth[futureMonth]) {

futureDayNumber -= daysInMonth[futureMonth];

futureMonth++;
if (futureMonth > 12) {

futureMonth = 1;

futureYear++;

// Display the future date

[Link]("%d days later: %s %d, %d\n", N, getMonthName(futureMonth),


futureDayNumber, futureYear);

} else {

[Link]("Incorrect day number. Program terminated.");

private static String getMonthName(int month) {

String[] monthNames = {"", "January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"};

return monthNames[month];

private static boolean isLeapYear(int year) {

return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

}
Variable Description:

2)

Algorithm:

1. Accept Input:
 Create a Scanner object to read input from the user.
 Prompt the user to enter a sentence terminated by '.', '?', or '!'.
 Read and store the entered sentence.
 Validate the terminating character. If it is not one of '.', '?', or '!', display an error
message and terminate the program.
2. Process Sentence:
 Display the header "WORD\t\tCOUNT".
 Split the sentence into words using a space as the delimiter.
 Sort the words alphabetically.
 Process each word:
 Display the word.
 Count the number of vowels and consonants in the word.
 Display the vowel and consonant counts in one column.
3. Helper Function:
 isVowel: Takes a character as input and returns true if it is a vowel (case-
insensitive), false otherwise.
4. Close Scanner:
 Close the Scanner object to prevent resource leaks.
Program code:
import [Link];

import [Link];

import [Link];

public class WordFrequencyAnalyzer {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Accept a sentence terminated by '.', '?', or '!'

[Link]("Enter a sentence (terminated by '.', '?', or '!'): ");

String sentence = [Link]();

// Validate the terminating character

char lastChar = [Link]([Link]() - 1);

if (lastChar != '.' && lastChar != '?' && lastChar != '!') {

[Link]("Incorrect terminating character. Invalid input.");

return;

// Process the sentence

processSentence(sentence);

// Close the scanner


[Link]();

private static void processSentence(String sentence) {

// Display the header

[Link]("WORD\t\tCOUNT");

// Split the sentence into words

String[] words = [Link](" ");

// Sort the words alphabetically

[Link](words);

// Process each word

for (String word : words) {

// Display the word

[Link](word + "\t\t");

// Count vowels and consonants

int vowelCount = 0;

int consonantCount = 0;

// Process each character in the word

for (char ch : [Link]()) {

if (isVowel(ch)) {
vowelCount++;

} else if ([Link](ch)) {

consonantCount++;

// Display the count in one column

[Link]("V: " + vowelCount + "\tC: " + consonantCount);

private static boolean isVowel(char ch) {

ch = [Link](ch);

return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';

Variable Description:
3)

Algorithm:

1. Accept Input:
 Create a Scanner object to read input from the user.
 Prompt the user to enter the number of rows (M) and columns (N).
 Validate that both M and N are greater than 2 and less than 10. If not, display an
error message and terminate the program.
 Declare a matrix A of size (M x N).
 Prompt the user to enter elements for the matrix A.
2. Display Original Matrix:
 Display the header "ORIGINAL MATRIX."
 Use a nested loop to display the elements of matrix A.
3. Rotate Matrix:
 Create a function rotateMatrix that takes a matrix as input and returns a new
matrix rotated by 270 degrees anti-clockwise.
 Display the header "ROTATED MATRIX (270 DEGREES ANTI-CLOCKWISE)."
 Call the rotateMatrix function on matrix A and display the rotated matrix.
4. Calculate Odd Sum:
 Create a function calculateOddSum that takes a matrix as input and returns the
sum of odd elements.
 Display the sum of odd elements calculated using the calculateOddSum function.
5. Close Scanner:
 Close the Scanner object to prevent resource leaks.
Program code:
import [Link];

public class MatrixOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Accept the dimensions of the matrix

[Link]("Enter the number of rows (M): ");


int M = [Link]();

[Link]("Enter the number of columns (N): ");

int N = [Link]();

// Validate the dimensions

if (M <= 2 || N <= 2 || M >= 10 || N >= 10) {

[Link]("Invalid input. Both M and N must be greater than 2 and less than 10.");

return;

// Declare and input elements into the matrix

int[][] matrixA = new int[M][N];

[Link]("Enter elements for the matrix:");

for (int i = 0; i < M; i++) {

for (int j = 0; j < N; j++) {

matrixA[i][j] = [Link]();

// (a) Display the input matrix

[Link]("\nORIGINAL MATRIX:");

displayMatrix(matrixA);

// (b) Rotate the matrix by 270 degrees anti-clockwise


int[][] rotatedMatrix = rotateMatrix(matrixA);

// Display the rotated matrix

[Link]("\nROTATED MATRIX (270 DEGREES ANTI-CLOCKWISE):");

displayMatrix(rotatedMatrix);

// (c) Calculate the sum of odd elements in the matrix

int oddSum = calculateOddSum(matrixA);

[Link]("\nSUM OF THE ODD ELEMENTS = " + oddSum);

[Link]();

private static void displayMatrix(int[][] matrix) {

for (int[] row : matrix) {

for (int element : row) {

[Link](element + "\t");

[Link]();

private static int[][] rotateMatrix(int[][] matrix) {

int rows = [Link];

int cols = matrix[0].length;


int[][] rotatedMatrix = new int[cols][rows];

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

rotatedMatrix[j][rows - 1 - i] = matrix[i][j];

return rotatedMatrix;

private static int calculateOddSum(int[][] matrix) {

int sum = 0;

for (int[] row : matrix) {

for (int element : row) {

if (element % 2 != 0) {

sum += element;

return sum;

}
Variable Description:

Common questions

Powered by AI

Helper methods promote efficiency by enabling code reuse, reducing redundancy across programs. By encapsulating specific tasks, such as checking leap years or retrieved structured data like month names, they prevent errors from copy-paste programming and provide centralized logic updates, enhancing maintainability and consistency .

Input validation ensures algorithm robustness by preventing invalid or unexpected input that could lead to crashes, incorrect computations, or security vulnerabilities. By checking constraints such as ranges for day numbers, sentence terminators, and matrix dimensions, algorithms maintain integrity and provide predictable outputs, which is vital for reliability .

Calculating the sum of odd numbers in a matrix helps characterize data by identifying elements' parity and focusing on specific subsets. It reveals patterns in distribution and frequency of odd versus even numbers, facilitating deeper insights into matrix structure and aiding in mathematical or statistical analysis .

When calculating a future date, key considerations include handling the leap year since February's days change from 28 to 29. It's crucial to update the days in February within the daysInMonth array when a year is leap. Calculating the future date involves adjusting the day number across months and potentially into a new year, demanding precise month-day mapping and incremental year updates when the day number exceeds a month's length .

Restricting matrix dimensions helps manage complexity by limiting the potential size and computational demand. This prevents excessive resource use and simplifies matrix operations such as rotation and summing odd elements by ensuring computational feasibility within small, manageable bounds. This dimensional constraint is crucial for testing and performance considerations .

Challenges include accounting for variable month lengths, leap years, and transitioning across years and time zones. Extending logic to scheduling demands handling business rules like daylight saving changes or working days, adding layers of complexity like recurrence patterns or holidays, which require sophisticated algorithms beyond simple day addition .

Sorting words alphabetically ensures uniform presentation and easier comparison, enhancing readability and structured output. It aids in identifying patterns or anomalies and reduces complexity in further string operations, setting a standard processing path that can affect subsequent data handling and displays .

The WordFrequencyAnalyzer ensures input validation by checking if the last character of the input sentence is '.', '?', or '!'. For processing, it first splits the sentence into words, sorts them alphabetically, and counts vowels and consonants per word, displaying each word with these counts. Validation and processing steps ensure systematic and correct analysis despite linguistic variations .

Rotating a matrix 270 degrees anti-clockwise involves interchanging the matrix’s row and column indices. The row index of the input matrix becomes the column index in the resulting matrix, and the columns are filled from bottom to top. This transformation effectively rotates elements as desired, reflecting foundational principles in matrix manipulation .

Helper functions like 'getMonthName' and 'isLeapYear' modularize the FutureDateCalculator by separating logical units of functionality, making the code easier to read and maintain. 'getMonthName' provides intuitive month names based on numerical input, while 'isLeapYear' encapsulates leap year logic, simplifying the main algorithm by abstracting complexity .

You might also like