Com Proj
Com Proj
Class: XI Section: C
Roll number: 24
Registration number: 2012/169
Subject: Computer
In a directory the names of streets and suburbs are shortened by replacing all vowels (a, e, i, o, u)
with its next vowel (in cyclic sequence) unless the vowel appears at the beginning of a word, in
which case it is kept unchanged. Write a program that will automatically shorten any address in this
manner. Punctuation and numbers must be reproduced as in the input.
Example 1:
Input: Woodside Output: Wudsodi
Example 2:
Input: Observatory Output: Obsirvetury
Design a class named “VowelsReplaced” having the following data members and member
functions are:
Data Members:
String streets[]; - stores a list of street names within an array
int size - stores the size of the array
Member Functions:
void accept( ) : accept the street names from the user.
void replaceVowels( ) : replace all the vowels in the street names as explained above.
void display( ) : display the list of street names.
ALGORITHM:-
accept():
Step 1: Start of algorithm.
Step 2: Accept the number of streets from the user in 'size'
Step 3: Initialize 'i' to 0
Step 4: Repeat steps 5-7 'size' times
Step 5: Accept the ith street name as the ith element of array data structure streets[]
Step 6: Increment 'i' by 1
Step 7: End of loop
Step 8: End of algorithm
replaceVowels():
Step 1: Start of algorithm.
Step 2: Repeat steps 3-18 for each street in the array streets[]
Step 3: Initialize an empty string 'str' to store the modified street name
Step 4: Convert the current street name to an array of characters 'streetChars'
Step 5: Repeat steps 6-17 for each character in 'streetChars'
Step 6: Retrieve the current character 'currentChar' from 'streetChars'
Step 7: Get the next vowel in cyclic sequence as 'nextVowel' using the helper function
getNextVowel()
Step 8: Check if 'currentChar' is the first character or not a vowel
Step 9: If true, append 'currentChar' to 'str'
Step 10: Else, skip consecutive occurrences of the same vowel and append 'nextVowel' to
'str'
Step 11: Repeat until no consecutive occurrences of the same vowel
Step 12: Increment the loop variable
Step 13: End of loop
Step 14: Update the ith street in the array streets[] with the modified 'str'
Step 15: End of loop
Step 16: End of algorithm
display():
Step 1: Start of algorithm.
Step 2: Print "Shortened Street Names:"
Step 3: Repeat steps 4-6 for each street in the array streets[]
Step 4: Print the ith street name
Step 5: Increment the loop variable
Step 6: End of loop
Step 7: End of algorithm
isVowel(char c):
Step 1: Start of algorithm.
Step 2: Convert 'c' to lowercase
Step 3: Check if 'c' is present in the string "aeiou"
Step 4: Return true if 'c' is a vowel, else return false
Step 5: End of algorithm
getNextVowel(char c):
Step 1: Start of algorithm.
Step 2: Convert 'c' to lowercase
Step 3: Get the index of 'c' in the string "aeiou"
Step 4: Calculate the next index in cyclic sequence as '(index + 1) % 5'
Step 5: Return the character at the calculated index in the string "aeiou"
Step 6: End of algorithm
main():
Step 1: Start of algorithm.
Step 2: Create an instance of the VowelsReplaced class as 'vr'
Step 3: Call the accept function of 'vr' to input street names from the user
Step 4: Call the replaceVowels function of 'vr' to replace vowels in street names
Step 5: Call the display function of 'vr' to show the shortened street names
Step 6: End of algorithm
SOURCE CODE:-
import java.util.Scanner;
class VowelsReplaced {
// Data Members
String[] streets;
int size;
Variable Data
Description of Variable Scope of Variable
Name Type
Array to store street names entered by the
streets String[] VowelsReplaced class
user
size int Number of streets entered by the user VowelsReplaced class
sc Scanner Scanner object for input accept method
Loop variable for iteration in accept and
i int accept and display methods
display methods
Temporary string variable to store modified
str String replaceVowels method
street names
Array to store characters of a street name
streetChars char[] replaceVowels method
during vowel replacement
accept and replaceVowels
j int Loop variable for iteration in inner loops
methods
Current character being processed in the
currentChar char replaceVowels method
inner loop
Next vowel in the cyclic sequence for
nextVowel char replaceVowels method
replacement
String containing vowels for checking and isVowel and getNextVowel
vowels String
replacement methods
OUTPUT:-
QUESTION 2:-
A number is well-ordered when its digits are in a numerically ascending order. E.g. 147 is well-
ordered but 174 is not. In a well-ordered number, each of the digits 1 - 9 may only be used once.
Write a program that will calculate the sum of all the well-ordered numbers that are possible with a
fixed number of digits.
Example:
Input: 2 Output: 1440
ALGORITHM:-
calcSum(d):
Step 1: Start of algorithm.
Step 2: If d is less than 1 or greater than 9, return 0 (invalid input).
Step 3: Initialize sum to 0.
Step 4: Create an array arr of size d.
Step 5: Loop i from 1 to (9 - d + 1):
a. Set arr[0] to i.
b. Add the result of calcSumR(arr, 1) to sum.
Step 6: Return the sum.
Step 7: End of algorithm.
calcSumR(arr, idx):
Step 1: Start of algorithm.
Step 2: If idx is equal to the length of arr:
a. Initialize num to 0.
b. Loop i from 0 to the length of arr:
i. Set num to (num * 10 + arr[i]).
c. Return num.
Step 3: Initialize sum to 0.
Step 4: Loop i from (arr[idx - 1] + 1) to 9:
a. Set arr[idx] to i.
b. Add the result of calcSumR(arr, idx + 1) to sum.
Step 5: Return sum.
Step 6: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create an instance of WellOrderedNumbers as 'w'.
Step 3: Create a Scanner object as 'sc'.
Step 4: Print "Enter the number of digits: ".
Step 5: Read an integer from the user into variable 'd'.
Step 6: Print "Sum of well-ordered numbers with " + d + " digits: " + w.calcSum(d).
Step 7: End of algorithm.
SOURCE CODE:-
import java.util.Scanner;
class WellOrderedNumbers {
// This Function initiates calcSumR which recursively calls itself to generate the sum of all d -
digit well ordered numbers
static int calcSum(int d) {
if (d < 1 || d > 9) {
return 0; // Invalid input, as the digits should be between 1 and 9
}
int sum = 0;
int[] arr = new int[d];
return sum;
}
return num;
}
int sum = 0;
for (int i = arr[idx - 1] + 1; i <= 9; i++) {
arr[idx] = i;
sum += calcSumR(arr, idx + 1);
}
return sum;
}
}
public class Init2{
public static void main(String[] args) {
WellOrderedNumbers w = new WellOrderedNumbers();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of digits: ");
int d = sc.nextInt();
System.out.println("Sum of well-ordered numbers with " + d + " digits: " + w.calcSum(d));
}
}
VARIABLE DESCRIPTION TABLE:-
Variable
Data Type Description of Variable Scope of Variable
Name
d int Number of digits entered by the user main method
w WellOrderedNumbers Instance of WellOrderedNumbers class main method
sc Scanner Scanner object for input main method
Accumulator for summing well-ordered
sum int calcSum method
numbers
calcSum and
Array to store the current well-ordered
arr int[] calcSumR
number being generated
methods
calcSum and
Loop variable for iteration in calcSum and
i int calcSumR
calcSumR methods
methods
Index to track the position in the arr array
idx int calcSumR method
during recursion
Temporary variable to store the generated
num int calcSumR method
well-ordered number during recursion
OUTPUT:-
QUESTION 3:-
Write a program that will find given words in the 8 by 8 word square below. You may assume that
the words appear in rows and read forward (L to R) or backwards (R to L). [Hint: As you use the
same word square all the time you can save time by hardcoding it into your program.]
Your program should print out the word and indicate the row and column where the word begins
and in which direction it proceeds (forwards or backwards).
Example:
Input: COLT
Output: COLT, row 4, column 3, forwards
ALGORITHM:-
search(word, square):
Step 1: Start of algorithm.
Step 2: Get the number of rows (rows) and columns (cols) in the word square.
Step 3: Loop through each row from 0 to rows - 1:
a. Loop through each column from 0 to cols - 1:
i. Check if the word can be found in the forward direction using searchForward function.
ii. If found, print the word, row, column, and direction (forwards).
iii. Check if the word can be found in the backward direction using searchBackward function.
iv. If found, print the word, row, column, and direction (backwards).
Step 4: If the word is not found in any direction, print "Word not found in the word square."
Step 5: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create a Scanner object as 'sc'.
Step 3: Hardcode the 8 by 8 word square matrix as 'square'.
Step 4: Initialize choice to 0.
Step 5: Loop until choice is not equal to 2:
a. Print menu options.
b. Read an integer choice from the user.
c. If choice is 1:
i. Print "Enter the word to search: ".
ii. Read a word from the user and convert it to uppercase.
iii. Call the search function with the word and the word square.
d. If choice is 2, print "Exiting the program."
e. If choice is not 1 or 2, print "Invalid choice. Please enter a valid option."
Step 6: Close the Scanner.
Step 7: End of algorithm.
SOURCE CODE:-
import java.util.Scanner;
import java.util.InputMismatchException;
switch (choice) {
case 1:
System.out.print("Enter the word to search: ");
String word = sc.next().toUpperCase();
search(word, square);
break;
case 2:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
sc.close();
}catch(InputMismatchException ime)
{
System.err.println(ime.getMessage());
}
}
OUTPUT:-
QUESTION 4:-
Write a recursive/iterative function which takes a number N as function argument and displays the
Hailstone Sequence of that number. The sequence should stop when the sequence reaches 1.
Definition: The Hailstone Sequence of numbers can be generated from a starting positive integer, N
by:
a) If N = 1 then the sequence ends.
b) If N is Even, then the next N of the sequence = n / 2.
c) If N is Odd, then the next N of the sequence = 3 × n + 1.
The (unproven) Collatz conjecture is that the Hailstone Sequence for any starting number always
terminates.
The Hailstone Sequence is also known as Hailstone Numbers because the values are usually subject
to multiple descents and ascents like hailstone in a cloud.
This sequence is also known as the Collatz Sequence.
Examples:
INPUT:
N=7
OUTPUT:
Hailstone Numbers: 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Number of steps required: 17
INPUT:
N=9
OUTPUT:
Hailstone Numbers: 9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1
Number of steps required: 20
ALGORITHM:-
displayHS(N):
Step 1: Start of algorithm.
Step 2: Initialize steps to 0.
Step 3: Print "Hailstone Numbers: ".
Step 4: Loop until N is not equal to 1:
a. Print the value of N followed by a comma and space.
b. Increment steps by 1.
c. If N is even:
i. Set N to N divided by 2.
d. Else:
i. Set N to 3 times N plus 1.
Step 5: Print the final value of N.
Step 6: Print "Number of steps required: " followed by the value of steps.
Step 7: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create a Scanner object as 'sc'.
Step 3: Print "Enter a positive integer N: ".
Step 4: Read an integer N from the user.
Step 5: Call the displayHS function with the value of N.
Step 6: Close the Scanner.
Step 7: End of algorithm.
SOURCE CODE:-
import java.util.Scanner;
class HailstoneSequence {
// Function to display the Hailstone Sequence and the number of steps required
static void displayHS(int N) {
int steps = 0;
System.out.print("Hailstone Numbers: ");
while (N != 1) {
System.out.print(N + ", ");
steps++;
if (N % 2 == 0) {
N /= 2;
} else {
N = 3 * N + 1;
}
}
System.out.println(N);
System.out.println("Number of steps required: " + steps);
}
Variable Data
Description of Variable Scope of Variable
Name Type
sc Scanner Scanner object for input main method
main method and
N int Positive integer entered by the user
displayHS method
Number of steps required to reach 1 in the
steps int displayHS method
Hailstone Sequence
OUTPUT:-
QUESTION 5:-
Design a class named “JatakaTales” having the following data members and data members:
Data Members :
String filename : stores the name of the text file(for eg., “jatakatales.txt”) containing the story of
fairy tales.
Member Functions:
void writeStory( ) : writes the stories in the form of paragraphs accepted from the user into the file
whose named is stored in string object “filename”.
void readStory( ) : reads the contents of the file whose named is stored in string object “filename”.
void addNewStory( ) : appends a new story to the file whose named is stored in string object
“filename”.
int countWords( ) : returns the count of the number of distinct words stored in the file.
Write a menu driven main( ) to invoke the above functions to perform the above mentioned
functions.
ALGORITHM:-
writeStory():
Step 1: Start of algorithm.
Step 2: Try to open a PrintWriter ('w') and BufferedReader ('r') for the specified filename in append
mode.
Step 3: Print "Enter the story paragraphs (Type 'exit' on a new line to stop):".
Step 4: Read lines from the user until "exit" is entered, and write each line to the file.
Step 5: Print "Story written successfully."
Step 6: Close the resources 'w' and 'r'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
:
readStory():
Step 1: Start of algorithm.
Step 2: Try to open a BufferedReader ('r') for the specified filename.
Step 3: Print "Contents of the file <filename>:".
Step 4: Read and print each line from the file until the end of the file is reached.
Step 5: Close the BufferedReader 'r'.
Step 6: Catch any IOException and print an error message if encountered.
Step 7: End of algorithm.
addNewStory():
Step 1: Start of algorithm.
Step 2: Try to open a PrintWriter ('w') and BufferedReader ('r') for the specified filename in append
mode.
Step 3: Print "Enter the new story paragraphs (Type 'exit' on a new line to stop):".
Step 4: Read lines from the user until "exit" is entered, and append each line to the file.
Step 5: Print "New story added successfully."
Step 6: Close the resources 'w' and 'r'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
countWords():
Step 1: Start of algorithm.
Step 2: Initialize count to 0.
Step 3: Try to open a BufferedReader ('r') for the specified filename.
Step 4: Read each line from the file:
a. Initialize inWord to false.
b. Loop through each character in the line:
i. If the character is whitespace, set inWord to false.
ii. Else if not inWord, increment count and set inWord to true.
Step 5: Return the final count.
Step 6: Close the BufferedReader 'r'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create an instance of the JatakaTales class as 't'.
Step 3: Create a new Scanner object as 'sc'.
Step 4: Print "Enter new file name: ".
Step 5: Read the filename from the user and set it in the 't.filename'.
Step 6: Create a new Scanner object as 's'.
Step 7: Initialize 'c' to 0.
Step 8: Loop until 'c' is not equal to 5:
a. Print the menu options.
b. Read the user's choice into 'c'.
c. Switch on 'c' and call the appropriate member function of 't'.
d. Catch any InputMismatchException and print an error message if encountered.
Step 9: End of algorithm.
SOURCE CODE:-
import java.io.*;
import java.util.Scanner;
import java.util.InputMismatchException;
class JatakaTales {
// Data Members
String filename;
String l;
while (!(l = r.readLine()).equalsIgnoreCase("exit")) {
w.println(l);
}
System.out.println("Story written successfully.");
} catch (IOException e) {
System.out.println("Error writing the story to the file.");
}
}
String l;
while ((l = r.readLine()) != null) {
System.out.println(l);
}
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}
String l;
while (!(l = r.readLine()).equalsIgnoreCase("exit")) {
w.println(l);
}
if (Character.isWhitespace(c)) {
inWord = false;
} else if (!inWord) {
count++;
inWord = true;
}
}
}
} catch (IOException e) {
System.out.println("Error counting words in the file.");
}
return count;
}
do {
try{
System.out.println("\nMenu:");
System.out.println("1. Write Story\n2. Read Story\n3. Add New Story\n4. Count Words\
n5. Exit");
System.out.print("Enter your choice (1-5): ");
c = s.nextInt();
switch (c) {
case 1:
t.writeStory();
break;
case 2:
t.readStory();
break;
case 3:
t.addNewStory();
break;
case 4:
System.out.println("Number of distinct words in the file: " + t.countWords());
break;
case 5:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}catch(InputMismatchException ime)
{
System.err.println(ime.getMessage());
}
} while (c != 5);
}
}VARIABLE DESCRIPTION TABLE:-
Variable
Data Type Description of Variable Scope of Variable
Name
t JatakaTales Instance of JatakaTales class main method
sc Scanner Scanner object for input main method
Scanner object for input (Menu
s Scanner main method
choices)
c int User's menu choice (1-5) main method
filename String Name of the file JatakaTales class
w PrintWriter Object to write into the file writeStory method
writeStory, readStory, and
r BufferedReader Object to read from the file
countWords methods
writeStory, readStory, and
l String Line read from the file
countWords methods
Array to store characters for
characters char[] countWords method
counting words
Flag to track if currently in a
inWord boolean countWords method
word
Variable
Data Type Description of Variable Scope of Variable
Name
Number of distinct words in the
count int countWords method
file
QUESTION 6:-
Design a class named “Product” having the following data members and member functions:
Data Members:
String pID : stores the product ID.
String pName : stores the name of the product
float pPrice : stores the price of the product
String suplr : stores the name of the supplier whose supplied the product
int qty : stores the quantity of the product in store
Member Functions:
void writeDetails( ) : writes the details of a product after accepting them from the user into the
binary file(“product.dat”), the function should have the provision of asking the user “Whether
he/she wants to add another record of a product into the file?” and work accordingly.
void readDetails( ) : reads the details of the products stored in the file.
Product search(String ProdID) : returns the Product details if the file contains any product with the
product ID ‘ProdID’ passed as a parameter to the function.
void updateProduct(String ProdID): updates the details of the Product having the product ID as
‘ProdID’
int countProd( ) : returns a count of the number of Products stored in the file.
Write a menu driven main( ) to invoke the above functions to perform the above mentioned
functions.
ALGORITHM:-
writeDetails():
Step 1: Start of algorithm.
Step 2: Try to open a DataOutputStream ('dout') for the file "product.dat" in append mode.
Step 3: Create a BufferedReader ('br') for reading input from the user.
Step 4: Loop:
a. Print "Enter product details:".
b. Read Product ID, Product Name, Product Price, Supplier Name, and Quantity from the user.
c. Write Product details to the file using 'dout'.
d. Print "Do you want to add another record? (yes/no): ".
e. Read user's response, and if it is "no", exit the loop.
Step 5: Print "Product details written to the file.".
Step 6: Close 'dout' and 'br'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
readDetails():
Step 1: Start of algorithm.
Step 2: Try to open a DataInputStream ('din') for the file "product.dat".
Step 3: Print "Product Details:".
Step 4: Loop until 'din' has available data:
a. Read and print Product ID, Product Name, Product Price, Supplier Name, and Quantity from
'din'.
Step 5: Close 'din'.
Step 6: Catch any IOException and print an error message if encountered.
Step 7: End of algorithm.
search(prodID):
Step 1: Start of algorithm.
Step 2: Initialize 'fP' to null.
Step 3: Try to open a DataInputStream ('din') for the file "product.dat".
Step 4: Loop until 'din' has available data:
a. Read Product ID, Product Name, Product Price, Supplier Name, and Quantity from 'din'.
b. If the read Product ID equals 'prodID', create a new Product ('fP') with the read details and
break the loop.
Step 5: Close 'din'.
Step 6: Return 'fP'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
updateProduct(prodID):
Step 1: Start of algorithm.
Step 2: Try to open a RandomAccessFile ('raf') for the file "product.dat" in read-write mode.
Step 3: Loop until 'raf' has data:
a. Read Product ID, Product Name, Product Price, Supplier Name, and Quantity from 'raf'.
b. If the read Product ID equals 'prodID':
i. Print "Enter updated product details:".
ii. Read and update Product Name, Product Price, Supplier Name, and Quantity.
iii. Move the file pointer back to update the record.
iv. Write updated details to 'raf'.
v. Print "Product details updated successfully." and break the loop.
Step 4: Close 'raf'.
Step 5: Catch any IOException and print an error message if encountered.
Step 6: End of algorithm.
countProd():
Step 1: Start of algorithm.
Step 2: Initialize 'count' to 0.
Step 3: Try to open a DataInputStream ('din') for the file "product.dat".
Step 4: Loop until 'din' has available data:
a. Read and ignore Product ID, Product Name, Product Price, Supplier Name, and Quantity from
'din'.
b. Increment 'count'.
Step 5: Close 'din'.
Step 6: Return 'count'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create an instance of the Product class as 'product'.
Step 3: Create a BufferedReader ('br') for reading input from the user.
Step 4: Declare variables 'choice', 'searchID', and 'updateID'.
Step 5: Loop until 'choice' is not equal to 6:
a. Print the menu options.
b. Read the user's choice into 'choice'.
c. Switch on 'choice' and call the appropriate member function of 'product'.
d. Catch any IOException and print an error message if encountered.
Step 6: End of algorithm.
SOURCE CODE:-
import java.io.*;
import java.io.IOException;
class Product {
// Data Members
String pID;
String pName;
float pPrice;
String suplr;
int qty;
do {
System.out.println("Enter product details:");
System.out.print("Product ID: ");
pID = br.readLine();
System.out.print("Product Name: ");
pName = br.readLine();
System.out.print("Product Price: ");
pPrice = Float.parseFloat(br.readLine());
System.out.print("Supplier Name: ");
suplr = br.readLine();
System.out.print("Quantity: ");
qty = Integer.parseInt(br.readLine());
// Writing details to the file
dout.writeUTF(pID);
dout.writeUTF(pName);
dout.writeFloat(pPrice);
dout.writeUTF(suplr);
dout.writeInt(qty);
return fP;
}
// Member Function to update product details by ID
void updateProduct(String prodID) {
try {
RandomAccessFile raf = new RandomAccessFile("product.dat", "rw");
while (raf.getFilePointer() < raf.length()) {
pID = raf.readUTF();
pName = raf.readUTF();
pPrice = raf.readFloat();
suplr = raf.readUTF();
qty = raf.readInt();
if (pID.equals(prodID)) {
System.out.println("Enter updated product details:");
System.out.print("Product Name: ");
pName = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.print("Product Price: ");
pPrice = Float.parseFloat(new BufferedReader(new
InputStreamReader(System.in)).readLine());
System.out.print("Supplier Name: ");
suplr = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.print("Quantity: ");
qty = Integer.parseInt(new BufferedReader(new
InputStreamReader(System.in)).readLine());
// Move the file pointer back to update the record
raf.seek(raf.getFilePointer() - (pID.length() + pName.length() + 12));
// Update product details
raf.writeUTF(pName);
raf.writeFloat(pPrice);
raf.writeUTF(suplr);
raf.writeInt(qty);
System.out.println("Product details updated successfully.");
break;
}
}
raf.close();
} catch (IOException e) {
System.out.println("Error updating product details in the file.");
}
}
Variable
Data Type Description of Variable Scope of Variable
Name
product Product Instance of Product class main method
Object for reading input from
br BufferedReader main method
the console
choice int User's menu choice (1-6) main method
main method and switch cases 3
searchID String Product ID for search
and 4
updateID String Product ID for update main method and switch case 4
fP Product Instance of Product class switch case 3
count int Number of products count switch case 5
pID String Product ID Product class
pName String Product Name Product class
pPrice float Product Price Product class
suplr String Supplier Name Product class
qty int Quantity Product class
Object for writing into the
dout DataOutputStream writeDetails method
binary file
Object for reading from the readDetails, search, and
din DataInputStream
binary file updateProduct methods
Object for random access to
raf RandomAccessFile updateProduct method
the binary file
OUTPUT:-
QUESTION 7:-
Write a program to read the contents of text file named “Para.txt” and do the following :
count and display the number of sentences,
display the sentence having the maximum number of words present in it,
count and display the number of words starting with a vowel,
display the frequency of longest word within the file.
ALGORITHM:-
countSentences():
Step 1: Start of algorithm.
Step 2: Initialize 'sCount' to 0.
Step 3: Try to open a BufferedReader ('reader') for the file "Para.txt".
Step 4: Loop until 'reader' has data:
a. Read a line from 'reader'.
b. Loop through each character in the line:
i. If the character is '.', '!', or '?', increment 'sCount'.
Step 5: Close 'reader'.
Step 6: Return 'sCount'.
Step 7: Catch any IOException and print an error message if encountered.
Step 8: End of algorithm.
displayMaxWordsSentence():
Step 1: Start of algorithm.
Step 2: Initialize 'mWCount' to 0 and 'mWSentence' to an empty string.
Step 3: Try to open a BufferedReader ('reader') for the file "Para.txt".
Step 4: Loop until 'reader' has data:
a. Read a line from 'reader'.
b. Initialize 'wCount' to 0 and 'currWord' to an empty string.
c. Loop through each character in the line:
i. If the character is whitespace or the last character in the line:
- If 'currWord' is not empty, increment 'wCount'.
- If 'wCount' is greater than 'mWCount', update 'mWCount' and 'mWSentence'.
d. Print "Sentence with the maximum number of words:".
e. Print 'mWSentence'.
Step 5: Close 'reader'.
Step 6: Catch any IOException and print an error message if encountered.
Step 7: End of algorithm.
countVowelWords():
Step 1: Start of algorithm.
Step 2: Initialize 'vWCount' to 0.
Step 3: Try to open a BufferedReader ('reader') for the file "Para.txt".
Step 4: Loop until 'reader' has data:
a. Read a line from 'reader'.
b. Loop through each character in the line:
i. If the character is whitespace or the last character in the line:
- If 'currWord' is not empty and the first character is a vowel, increment 'vWCount'.
c. Close 'reader'.
Step 5: Return 'vWCount'.
Step 6: Catch any IOException and print an error message if encountered.
Step 7: End of algorithm.
displayLongestWordFrequency():
Step 1: Start of algorithm.
Step 2: Initialize 'lWFrequency' to 0 and 'lWord' to an empty string.
Step 3: Try to open a BufferedReader ('reader') for the file "Para.txt".
Step 4: Loop until 'reader' has data:
a. Read a line from 'reader'.
b. Initialize 'currWord' to an empty string.
c. Loop through each character in the line:
i. If the character is whitespace or the last character in the line:
- If 'currWord' is longer than 'lWord', update 'lWord' and set 'lWFrequency' to 1.
- If 'currWord' is equal in length to 'lWord', increment 'lWFrequency'.
d. Print "Frequency of the longest word (" + 'lWord' + "): " + 'lWFrequency'.
Step 5: Close 'reader'.
Step 6: Catch any IOException and print an error message if encountered.
Step 7: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Declare 'c'.
Step 3: Loop until 'c' is not equal to 5:
a. Print the menu options.
b. Read the user's choice into 'c'.
c. Switch on 'c' and call the appropriate member function.
d. Catch any IOException and print an error message if encountered.
Step 4: End of algorithm.
SOURCE CODE:-
import java.io.*;
class TextAnalyzer {
// Member Function to count and display the number of sentences in the file
static int countSentences() {
int sCount = 0;
return sCount;
}
// Member Function to display the sentence with the maximum number of words
static void displayMaxWordsSentence() {
int mWCount = 0;
String mWSentence = "";
try (BufferedReader reader = new BufferedReader(new FileReader("Para.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
int len = line.length();
int wCount = 0;
String currWord = "";
if (!currWord.isEmpty()) {
wCount++;
currWord = "";
}
} else {
currWord += c;
}
}
// Member Function to count and display the number of words starting with a vowel
static int countVowelWords() {
int vWCount = 0;
currWord = "";
} else {
currWord += c;
}
}
}
} catch (IOException e) {
System.out.println("Error reading the file.");
}
return vWCount;
}
// Member Function to display the frequency of the longest word in the file
static void displayLongestWordFrequency() {
int lWFrequency = 0;
String lWord = "";
currWord = "";
} else {
currWord += c;
}
}
}
do {
System.out.println("\nMenu:");
System.out.println("1. Count and Display Number of Sentences");
System.out.println("2. Display Sentence with Maximum Words");
System.out.println("3. Count and Display Number of Words Starting with a Vowel");
System.out.println("4. Display Frequency of Longest Word");
System.out.println("5. Exit");
System.out.print("Enter your choice (1-5): ");
c = Integer.parseInt(br.readLine());
switch (c) {
case 1:
int sCount = countSentences();
System.out.println("Number of Sentences: " + sCount);
break;
case 2:
displayMaxWordsSentence();
break;
case 3:
int vWCount = countVowelWords();
System.out.println("Number of Words Starting with a Vowel: " + vWCount);
break;
case 4:
displayLongestWordFrequency();
break;
case 5:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (c != 5);
}
}
VARIABLE DESCRIPTION TABLE:-
Variable Description of
Data Type Scope of Variable
Name Variable
Object for reading
br BufferedReader input from the main method
console
User's menu choice
c int main method and switch cases
(1-5)
Number of
sCount int countSentences method
sentences
Maximum word
mWCount int count among displayMaxWordsSentence method
sentences
Sentence with the
mWSentence String maximum number displayMaxWordsSentence method
of words
Number of words
vWCount int starting with a countVowelWords method
vowel
Frequency of the
lWFrequency int displayLongestWordFrequency method
longest word
lWord String Longest word displayLongestWordFrequency method
countSentences, displayMaxWordsSentence,
Object for reading
reader BufferedReader countVowelWords, and
from the file
displayLongestWordFrequency methods
OUTPUT:-
QUESTION 8:-
Write a program to write the following details of a student into a binary file(“Student.bin”) and do
the following operations on the different records of students stored in the file:
write the details of the student(Stud_ID, S_Name,Eng, Maths, Sc, SSc) – [all subject marks
accepted are out of 100 ]
Display the contents of the binary file.
Search for a specific student with an ID, accepted from the user.
Edit the marks obtained in the subjects for a student whose ID is accepted from the user.
Display the list of Students in Descending order of their Percentage marks.
Remove the details of a specific student whose ID is accepted from the user.
ALGORITHM:-
writeStudentDetails():
Step 1: Start of algorithm.
Step 2: Create a DataOutputStream to write to the binary file "Student.bin".
Step 3: Create a BufferedReader to read input from the user.
Step 4: Prompt the user to enter student details (ID, Name, Marks in English, Maths, Science,
Social Science).
Step 5: Read the entered values and write them to the file using dataOutputStream.
Step 6: Print "Student details written to the file."
Step 7: End of algorithm.
displayContents():
Step 1: Start of algorithm.
Step 2: Create a DataInputStream to read from the binary file "Student.bin".
Step 3: Print "Student Details:".
Step 4: Loop while there is data available in the file:
a. Read and print Student ID, Student Name, Marks in English, Maths, Science, and Social
Science.
Step 5: End of algorithm.
searchStudent():
Step 1: Start of algorithm.
Step 2: Create a DataInputStream to read from the binary file "Student.bin".
Step 3: Create a BufferedReader to read input from the user.
Step 4: Prompt the user to enter the Student ID to search.
Step 5: Read the entered ID and search for the student in the file.
Step 6: If found, print the student details; otherwise, print "Student not found with ID."
Step 7: End of algorithm.
editStudentMarks():
Step 1: Start of algorithm.
Step 2: Create a RandomAccessFile to read and write the binary file "Student.bin".
Step 3: Create a BufferedReader to read input from the user.
Step 4: Prompt the user to enter the Student ID to edit marks.
Step 5: Read the entered ID and search for the student in the file.
Step 6: If found, prompt the user to enter updated marks and update the file.
Step 7: Print "Marks updated successfully" if successful, otherwise print "Student not found with
ID."
Step 8: Close the RandomAccessFile.
Step 9: End of algorithm.
displayDescendingOrder():
Step 1: Start of algorithm.
Step 2: Create a RandomAccessFile to read the binary file "Student.bin".
Step 3: Create an array 'students' of Student objects.
Step 4: Read student records from the file and store them in the 'students' array.
Step 5: Implement Bubble Sort to sort 'students' in descending order based on percentage.
Step 6: Print the sorted list of students with their ID, Name, and Percentage.
Step 7: Close the RandomAccessFile.
Step 8: End of algorithm.
removeStudentDetails():
Step 1: Start of algorithm.
Step 2: Create a RandomAccessFile to read and write the binary file "Student.bin".
Step 3: Create a BufferedReader to read input from the user.
Step 4: Prompt the user to enter the Student ID to remove.
Step 5: Read the entered ID and search for the student in the file.
Step 6: If found, remove the student details from the file.
Step 7: Print "Student details removed successfully" if successful, otherwise print "Student not
found with ID."
Step 8: Close the RandomAccessFile.
Step 9: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create a BufferedReader for user input.
Step 3: Initialize 'choice' to 0.
Step 4: Start a do-while loop until 'choice' is 7:
a. Print the menu.
b. Read the user's choice.
c. Use a switch statement to execute the corresponding function based on the choice.
Step 5: End of algorithm.
SOURCE CODE:-
import java.io.*;
class StudentManager {
// Member Function to write student details into the binary file
static void writeStudentDetails() {
try (DataOutputStream dataOutputStream = new DataOutputStream(new
FileOutputStream("Student.bin", true))) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
if (studID.equals(searchID)) {
System.out.println("Student Found:\nStudent ID: " + studID +
"\nStudent Name: " + sName + "\nEnglish: " + eng +
"\nMaths: " + maths + "\nScience: " + sc + "\nSocial Science: " + sSc);
found = true;
break;
}
}
if (!found) {
System.out.println("Student not found with ID: " + searchID);
}
} catch (IOException e) {
System.out.println("Error searching for the student in the file.");
}
}
if (studID.equals(editID)) {
System.out.println("Enter updated marks for the student:");
System.out.print("Marks in English: ");
eng = Integer.parseInt(br.readLine());
System.out.print("Marks in Maths: ");
maths = Integer.parseInt(br.readLine());
System.out.print("Marks in Science: ");
sc = Integer.parseInt(br.readLine());
System.out.print("Marks in Social Science: ");
sSc = Integer.parseInt(br.readLine());
if (!found) {
System.out.println("Student not found with ID: " + editID);
}
raf.close();
} catch (IOException e) {
System.out.println("Error editing student marks in the file.");
}
}
// Member Function to display the list of students in descending order of their percentage marks
static void displayDescendingOrder() {
// Implementing sorting logic (Bubble Sort) based on percentage marks
try {
RandomAccessFile raf = new RandomAccessFile("Student.bin", "rw");
raf.close();
} catch (IOException e) {
System.out.println("Error displaying students in descending order.");
}
}
raf.close();
} catch (IOException e) {
System.out.println("Error removing student details from the file.");
}
}
// Constructor
Student(String studID, String sName, int eng, int maths, int sc, int sSc) {
this.studID = studID;
this.sName = sName;
this.eng = eng;
this.maths = maths;
this.sc = sc;
this.sSc = sSc;
}
do {
System.out.println("\nMenu:");
System.out.println("1. Write Student Details\n2. Display Contents\n3. Search Student\n4.
Edit Student Marks\n5. Display Descending Order\n6. Remove Student Details\n7. Exit");
System.out.print("Enter your choice (1-7): ");
choice = Integer.parseInt(br.readLine());
switch (choice) {
case 1:
writeStudentDetails();
break;
case 2:
displayContents();
break;
case 3:
searchStudent();
break;
case 4:
editStudentMarks();
break;
case 5:
displayDescendingOrder();
break;
case 6:
removeStudentDetails();
break;
case 7:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
Description of
Variable Name Data Type Scope of Variable
Variable
Object for reading
br BufferedReader input from the main method
console
Object for writing
dataOutputStream DataOutputStream data to the binary writeStudentDetails method
file
writeStudentDetails, searchStudent,
studID String Student ID editStudentMarks, and
removeStudentDetails methods
writeStudentDetails, searchStudent,
sName String Student Name editStudentMarks, and
removeStudentDetails methods
writeStudentDetails, displayContents,
eng int Marks in English searchStudent, editStudentMarks, and
removeStudentDetails methods
writeStudentDetails, displayContents,
maths int Marks in Maths searchStudent, editStudentMarks, and
removeStudentDetails methods
sc int Marks in Science writeStudentDetails, displayContents,
searchStudent, editStudentMarks, and
Description of
Variable Name Data Type Scope of Variable
Variable
removeStudentDetails methods
writeStudentDetails, displayContents,
Marks in Social
sSc int searchStudent, editStudentMarks, and
Science
removeStudentDetails methods
Object for reading
displayContents, searchStudent
dataInputStream DataInputStream data from the binary
methods
file
Student ID for
removeID String removeStudentDetails method
removing details
Flag indicating
searchStudent, editStudentMarks, and
found boolean whether a student is
removeStudentDetails methods
found or not
Random access file
editStudentMarks,
object for reading
raf RandomAccessFile displayDescendingOrder, and
and writing student
removeStudentDetails methods
details
Array to store
students Student[] Student objects for displayDescendingOrder method
sorting
Count of students in
count int displayDescendingOrder method
the array for sorting
User's menu choice
choice int main method and switch cases
(1-7)
Temporary variable
temp Student for swapping displayDescendingOrder method
students in sorting
OUTPUT:-
QUESTION 9:-
A sentence is terminated by either “ . ” , “ ! ” or “ ? ” followed by a space. Input a piece of text
consisting of sentences. Assume that there will be a maximum of 10 sentences in a block.
Write a program to:
(i) Obtain the length of the sentence (measured in words) and the frequency of vowels in each
sentence.
(ii) Generate the output as shown below using the given data
Sample data:
INPUT:-
HELLO! HOW ARE YOU? HOPE EVERYTHING IS FINE. BEST OF LUCK.
OUTPUT:-
Sentence No. of Vowels No. of words
---------------------------------------------------------- ---------------------------
121
253
384
433
ALGORITHM:-
obtainSentenceDetails(sentences):
Step 1: Start of algorithm.
Step 2: Print the header for the details table.
Step 3: Loop through each sentence in 'sentences':
a. Trim the sentence.
b. Call the 'countVowels' function to obtain the vowel count.
c. Call the 'countWords' function to obtain the word count.
d. Print the sentence number, vowel count, and word count in a formatted manner.
Step 4: End of algorithm.
generateOutput(sentences):
Step 1: Start of algorithm.
Step 2: Print the header for the output table.
Step 3: Loop through each sentence in 'sentences':
a. Trim the sentence.
b. Call the 'countVowels' function to obtain the vowel count.
c. Call the 'countWords' function to obtain the word count.
d. Print the sentence number, vowel count, and word count in a formatted manner.
Step 4: End of algorithm.
countVowels(sentence):
Step 1: Start of algorithm.
Step 2: Initialize 'vowelCount' to 0.
Step 3: Loop through each character in 'sentence':
a. If the lowercase of the character is a vowel (a, e, i, o, u):
i. Increment 'vowelCount'.
Step 4: Return 'vowelCount'.
Step 5: End of algorithm.
countWords(sentence):
Step 1: Start of algorithm.
Step 2: Split 'sentence' into an array of words using "\\s+" as the delimiter.
Step 3: Return the length of the array as the word count.
Step 4: End of algorithm.
main():
Step 1: Start of algorithm.
Step 2: Create a Scanner ('sc') for user input.
Step 3: Prompt the user to enter a piece of text consisting of sentences (max 10 sentences).
Step 4: Read the input text and split it into sentences using "[.!?]\\s" as the delimiter.
Step 5: Initialize 'choice' to 0.
Step 6: Start a do-while loop until 'choice' is 3:
a. Print the menu.
b. Read the user's choice.
c. Use a switch statement to execute the corresponding function based on the choice:
i. Case 1: Call 'obtainSentenceDetails' with the 'sentences' array.
ii. Case 2: Call 'generateOutput' with the 'sentences' array.
iii. Case 3: Print "Exiting the program."
iv. Default: Print "Invalid choice. Please enter a valid option."
Step 7: Close the Scanner.
Step 8: End of algorithm.
SOURCE CODE:-
import java.util.Scanner;
public class SentenceAnalyzer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Input a piece of text consisting of sentences
System.out.println("Enter a piece of text consisting of sentences (max 10 sentences):");
String inputText = sc.nextLine();
// Split the input text into sentences
String[] sentences = inputText.split("[.!?]\\s");
// Menu-Driven Main Function
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Obtain Length of Sentences and Frequency of Vowels");
System.out.println("2. Generate Output");
System.out.println("3. Exit");
System.out.print("Enter your choice (1-3): ");
choice = sc.nextInt();
switch (choice) {
case 1:
obtainSentenceDetails(sentences);
break;
case 2:
generateOutput(sentences);
break;
case 3:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (choice != 3);
sc.close();
}
// Function to obtain the length of the sentence (measured in words) and the frequency of vowels
in each sentence
private static void obtainSentenceDetails(String[] sentences) {
System.out.println("----------------------------------------------------------");
System.out.println("Sentence No. of Vowels No. of Words");
System.out.println("----------------------------------------------------------");
for (int i = 0; i < sentences.length && i < 10; i++) {
String sentence = sentences[i].trim();
int vowelCount = countVowels(sentence);
int wordCount = countWords(sentence);
System.out.println(i + 1 + " " + vowelCount + " " + wordCount);
}
}
Variable Data
Description of Variable Scope of Variable
Name Type
Scanner object for reading
sc Scanner main method
input from the console
Input text consisting of
inputText String main method
sentences
Array to store individual main method, obtainSentenceDetails
sentences String[]
sentences after splitting method, generateOutput method
choice int User's menu choice (1-3) main method and switch cases
Loop variable for iterating obtainSentenceDetails method and
i int
through sentences generateOutput method
Individual sentence extractedobtainSentenceDetails method and
sentence String
from the array generateOutput method
Count of vowels in a obtainSentenceDetails method and
vowelCount int
sentence generateOutput method
obtainSentenceDetails method and
wordCount int Count of words in a sentence
generateOutput method
Array to store individual
words String[] countWords method
words after splitting
OUTPUT:-
QUESTION 10:-
A set is a collection in which there is no duplication of elements. A multi set is- single dimension
collection in which elements can be duplicated. For example s = {1, 2, 3, 4} is a set with integer
elements. While ms ={1,2,3,1,3} is a multi set. Following are some member functions of the class
Multiset (which defines multi sets with integer elements)
Member functions/methods: -
Multiset( ) //constructor,
void readlist( ) //to input integers ,
void displaylist( ) //to display the integers,
int isSet() //which returns 1 if the multiset object is a set otherwise return 0.
void convert()// converts a multi set into set.
Define class with all member function do not write main().
ALGORITHM:-
readlist()
Step 1: Start of algorithm.
Step 2: Create a Scanner object 'sc'.
Step 3: Prompt the user to enter the number of elements in the multiset.
Step 4: Read the entered size and store it in 'size'.
Step 5: Print a message to enter the elements of the multiset.
Step 6: Initialize a loop with 'i' set to 0.
Step 7: Read an integer from the user and store it in arr[i].
Step 8: Increment 'i' by 1.
Step 9: Repeat steps 7 and 8 until 'i' reaches 'size'.
Step 10: End of algorithm.
displaylist():
Step 1: Start of algorithm.
Step 2: Print "Multiset: { ".
Step 3: Initialize a loop with 'i' set to 0.
Step 4: Loop over arr from 0 to the last non-zero element.
a. Print the current element followed by a space.
Step 5: Print "}".
Step 6: End of algorithm.
isSet():
Step 1: Start of algorithm.
Step 2: Initialize a loop with 'i' from 0 to the last non-zero element in arr.
Step 3: Initialize a nested loop with 'j' from i+1 to the last non-zero element in arr.
Step 4: If arr[i] is equal to arr[j], return 0 (not a set).
Step 5: If the nested loop completes without returning, continue with the outer loop.
Step 6: Return 1 (is a set) if the outer loop completes.
Step 7: End of algorithm.
convert():
Step 1: Start of algorithm.
Step 2: Initialize a loop with 'i' from 0 to the last non-zero element in arr.
Step 3: Initialize a nested loop with 'j' from i+1 to the last non-zero element in arr.
Step 4: If arr[i] is equal to arr[j]:
a. Initialize another loop from j to arr.length-1.
i. Shift elements to the left to remove duplicates.
b. Set the last element of arr to 0.
c. Decrement 'j' to recheck the current position.
Step 5: Continue with the outer loop if the nested loop completes.
Step 6: End of algorithm.
Main Method:
Step 1: Start of algorithm.
Step 2: Create a Multiset object 'ms'.
Step 3: Call ms.readlist() to input integers into the multiset.
Step 4: Call ms.displaylist() to display the integers in the multiset.
Step 5: Check if ms.isSet() is 1 (true):
a. Print "The multiset is a set."
Step 6: If ms.isSet() is 0 (false):
a. Print "The multiset is not a set."
b. Call ms.convert() to convert the multiset into a set.
c. Call ms.displaylist() to display the modified multiset.
Step 7: End of algorithm.
SOURCE CODE:-
import java.util.Scanner;
class Multiset {
// Data member
int[] arr;
// Constructor
Multiset() {
arr = new int[50]; // Assuming a maximum of 50 elements in the multiset
}
Variable Data
Description of Variable Scope of Variable
Name Type
arr int[] Array to store elements of the multiset Class-wide
Scanner object for reading input from the
sc Scanner readlist method
console
size int Number of elements in the multiset readlist method
Loop variables for iterating through the readlist, displaylist, isSet,
i, j, k int
elements convert methods
Result indicating whether the multiset is a
isSetResult int isSet method
set (1 for true, 0 for false)
OUTPUT:-