0% found this document useful (0 votes)
7 views9 pages

Future Date and Word Analysis in Java

This program calculates future dates, analyzes word frequencies in a string, and performs operations on matrices. For future dates, it accepts a starting date and year, adds days, and calculates the future date accounting for leap years. For word frequency, it tokenizes a string, counts vowels and consonants in each word and displays the results. For matrices, it accepts a 2D array as input, displays the original and rotated matrices, and calculates the sum of odd elements in the rotated matrix.

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)
7 views9 pages

Future Date and Word Analysis in Java

This program calculates future dates, analyzes word frequencies in a string, and performs operations on matrices. For future dates, it accepts a starting date and year, adds days, and calculates the future date accounting for leap years. For word frequency, it tokenizes a string, counts vowels and consonants in each word and displays the results. For matrices, it accepts a 2D array as input, displays the original and rotated matrices, and calculates the sum of odd elements in the rotated matrix.

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)

Program code:
import [Link].*;

class FutureDateCalculator2

public static void main(String args[])

Scanner sc=new Scanner([Link]);

[Link]("Enter day Number:");

int d=[Link]();

[Link]("Enter year:");

int y=[Link]();

[Link]("Enter date after:");

int n=[Link]();

if((d>366)||(y<1000 && y>9999)||(n<1 && n>100))

[Link]("Invalid Input");

else

calculate(d,y);

d=d+n;

if(d>365 && y%4!=0)

d=d-365;

y++;

}
else if(d>366 && y%4==0)

d=d-366;

y++;

calculate(d,y);

public static void calculate(int x,int yr)

String
m[]={"","January","February","March","April","May","June","July","August","September","October","No
vember","December"};

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

if(yr%4==0)

day[2]=29;

int i=0;

while(x>day[i])

x=x-day[i];

i++;

String s="";

if(x%10 ==1)

s="st";

else if(x%10 ==2)

s="nd";

else if(x%10==3)
s="rd";

else

s="th";

[Link](x+s+" "+m[i]+" "+yr);

Algorithm:
1. Accept Input:
 Use a Scanner to accept input for the day number, year, and the number of days
to add (n).
 Check for invalid input conditions (day number greater than 366, year not in the
range 1000 to 9999, and n not in the range 1 to 100).
2. Calculate Future Date:
 Call the calculate function with the initial day number ( d) and year (y).
 Add the specified number of days ( n) to the day number (d).
 Adjust the day number and year if it exceeds the total number of days in a year
(considering leap years).
 Call the calculate function again with the updated day number and year.
3. Calculate Function:
 Takes the day number ( x) and year (yr) as input.
 Initializes arrays for month names ( m) and the number of days in each month
(day).
 Adjusts the number of days in February for leap years.
 Finds the month and day corresponding to the input day number.
 Prints the calculated date in the format "day month year."
Variable description:

2)Program code:
import [Link].*;

class WordFrequencyAnalyzer10

public static void main(String args[])

Scanner sc=new Scanner([Link]);

[Link]("Enter the String");

String str=[Link]();

str=[Link]();

StringTokenizer st=new StringTokenizer(str,"!?,.' '");

int l=[Link]();

for(int i=0;i<l;i++)

String x=[Link]();

int v=0,c=0;
for(int j=0;j<[Link]();j++)

char ch=[Link](j);

if([Link](ch))

if(ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')

v++;

else

c++;

else

[Link]("Invalid Input");

return;

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

[Link](x+" ");

for(int j=1;j<=v;j++)

[Link]("V");

[Link]();

[Link](" ");

for(int j=1;j<=c;j++)

[Link]("C");

[Link]();

}
Algorithm:
1. Accept Input:
 Create a Scanner to read input from the user.
 Prompt the user to enter a string.
 Convert the string to uppercase to handle both uppercase and lowercase letters.
 Use StringTokenizer to tokenize the string using delimiters ('!', '?', ',', '.', ' ', and
single quotes).
2. Tokenization and Processing:
 Count the number of tokens obtained from the StringTokenizer .
 Iterate through each token:
 Initialize variables v and c to count vowels and consonants.
 Iterate through each character in the token.
 Check if the character is a letter. If not, display an "Invalid Input" message
and terminate.
 Count vowels ('A', 'E', 'I', 'O', 'U') and consonants.
 Display the word, vowel count, and consonant count in the specified
format.
Variable description:

3)
Program code:
import [Link].*;

class MatrixOperations2

public static void main(String args[])

Scanner sc=new Scanner([Link]);

[Link]("Enter rows and columns");

int m=[Link]();

int n=[Link]();

if((m<=2 || m>=10)||(n<=2 || n>=10))

{ [Link]("Invalid Input");

[Link](0);

int a[][]=new int[m][n];

[Link]("Enter array elements");

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

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

[Link]("Original Matrix");

for(int i=0;i<m;i++)

for(int j=0;j<n;j++)

[Link](a[i][j]+" ");
}

[Link]();

[Link]("Rotated Matrix");

int s=0;

for(int j=0;j<n;j++)

for(int i=m-1;i>=0;i--)

[Link](a[i][j]+" ");

if(a[i][j]%2!=0)

s=s+a[i][j];

[Link]();

[Link]("The sum of odd elements is="+s);

Algorithm:
1. Accept Input:
 Create a Scanner to read input from the user.
 Prompt the user to enter the number of rows ( m) and columns (n).
 Check for invalid input conditions (rows or columns less than or equal to 2, or
greater than or equal to 10). If invalid, display an "Invalid Input" message and
terminate the program.
 Declare a 2D array (a) of size (m x n) to store array elements.
 Prompt the user to enter array elements and populate the array.
2. Display Original Matrix:
 Display the header "Original Matrix."
 Use nested loops to display the elements of the original matrix.
3. Rotate Matrix and Sum Odd Elements:
 Display the header "Rotated Matrix."
 Use nested loops to traverse and print the rotated matrix (by columns in reverse
order).
 If an element in the rotated matrix is odd, accumulate its value in the variable s.
 Display the sum of odd elements (s).
Variable description:

Common questions

Powered by AI

The FutureDateCalculator2 program limits the input size by ensuring day numbers do not exceed 366, years are within 1000 to 9999, and additional days are between 1 and 100. Similarly, MatrixOperations2 restricts matrix dimensions to be greater than 2 and less than 10. These limitations prevent excessive computational demands and avoid inefficient processing or potential memory issues, reflecting best practices in programming for ensuring robustness and preventing misuse through input validation and boundary checks, aligning with principles of defensive programming .

Both FutureDateCalculator2 and MatrixOperations2 implement input validation error handling but with different conditions. FutureDateCalculator2 checks for a day number exceeding 366, a year outside 1000–9999, and a day addition outside 1–100, outputting 'Invalid Input' if failed. MatrixOperations2 checks matrix dimension limits (2 < m, n < 10) and terminates with an error if incorrect. Both use conditional checks to prevent runtime errors and ensure valid input, demonstrating defensive programming practices, although MatrixOperations2 terminates the program using System.exit(0), whereas FutureDateCalculator2 continues to process input .

MatrixOperations2 calculates the sum of odd elements in the rotated matrix by first rotating the matrix 90 degrees. The rotated matrix is displayed column-wise in reverse order. For each element in this rotated view, the program checks if it is odd (i.e., not divisible by 2). If the element is odd, its value is added to the sum variable 's'. After processing all elements, the sum of odd elements is displayed .

The calculate method in FutureDateCalculator2 determines the month and day by initializing arrays for month names and the number of days in each month. It adjusts February's day count for leap years. Using a loop, the program iteratively subtracts the days of each month from the input day number until it identifies the month where the day falls. It calculates suffixes based on the remainder of the day divided by 10 to format the date correctly, which are then concatenated with the month and year for output .

The MatrixOperations2 program implements invalid input checks to ensure that the matrix dimensions (rows and columns) are within the acceptable range of greater than 2 and less than 10. These checks are important because they prevent the user from entering dimensions that would not be meaningful for the program's matrix operations, such as rotating or summing elements, thereby avoiding runtime errors and ensuring logical correctness of operations .

MatrixOperations2 handles the rotation by iterating through the matrix columns in descending row order. Specifically, for each column, it prints the elements from the bottom row up to the top, effectively achieving a 90-degree clockwise rotation of the matrix. The transformation results in a transposition where rows become columns in reverse order, enabling the matrix to be viewed from a different perspective, which is useful for various applications in computer graphics and data representation .

The FutureDateCalculator2 program handles leap years by checking if the year is divisible by 4. If the year is a leap year, the number of days in February is adjusted to 29. When calculating future dates, the program subtracts 366 days instead of 365 if the day number exceeds 366. This adjustment ensures the correct date is calculated for leap years .

FutureDateCalculator2 determines the ordinal suffix (st, nd, rd, th) for dates by evaluating the remainder of the day number when divided by 10. It assigns 'st' for remainders of 1 (1st, 21st), 'nd' for 2 (2nd, 22nd), 'rd' for 3 (3rd, 23rd), and 'th' for other cases. This strategy is generally correct but may falter with exceptions like 11th, 12th, 13th, due to ignoring cases where numbers like 11-13 do not follow the typical pattern. This could cause incorrect ordinal formatting in edge cases, though it handles most cases accurately .

The StringTokenizer in the WordFrequencyAnalyzer10 program is used to tokenize the input string into individual words based on specified delimiters such as '!', '?', ',', '.', ' ', and single quotes. This facilitates the program's ability to iterate through each word separately, count the vowels and consonants, and then display the counts accurately for each word without them being affected by punctuation or spacing .

WordFrequencyAnalyzer10 ensures only valid input characters by checking if each character in a token is a letter using the Character.isLetter method. If a non-letter character is detected, the program outputs 'Invalid Input' and terminates further execution. This mechanism ensures that only alphabetic characters are considered for vowel and consonant counting, maintaining data integrity and correctness of results .

You might also like