0% found this document useful (0 votes)
9 views88 pages

Com Proj

The document outlines a computer science project for Class XI, focusing on two main programming tasks: replacing vowels in street names and calculating the sum of well-ordered numbers. It includes detailed algorithms, source code in Java, and variable descriptions for both tasks. Additionally, it describes a word search program that identifies words in a predefined 8x8 word square, detailing the search algorithms for both forward and backward directions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views88 pages

Com Proj

The document outlines a computer science project for Class XI, focusing on two main programming tasks: replacing vowels in street names and calculating the sum of well-ordered numbers. It includes detailed algorithms, source code in Java, and variable descriptions for both tasks. Additionally, it describes a word search program that identifies words in a predefined 8x8 word square, detailing the search algorithms for both forward and backward directions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 88

Name: Rajrup Chattopadhyay

Class: XI Section: C
Roll number: 24
Registration number: 2012/169

Subject: Computer

Topic: class xi computer Science Project


work, I. s .c 2025
FINAL TERM
PROJECT
QUESTION 1:-

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;

// Function to accept street names from the user


void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of streets: ");
size = sc.nextInt();
streets = new String[size];
System.out.println("Enter the street names:");
for (int i = 0; i < size; i++) {
streets[i] = sc.next();
}
}

// Function to replace vowels in street names


void replaceVowels() {
for (int i = 0; i < size; i++) {
String str = "";
char[] streetChars = streets[i].toCharArray();
for (int j = 0; j < streetChars.length; j++) {
char currentChar = streetChars[j];
char nextVowel = getNextVowel(currentChar);
if (j == 0 || !isVowel(currentChar)) {
str += currentChar;
} else {
// Skip consecutive occurrences of the same vowel
while (j + 1 < streetChars.length && streetChars[j + 1] == currentChar) {
j++;
}
str += nextVowel;
}
}
streets[i] = str;
}
}

// Function to display the list of street names


void display() {
System.out.println("Shortened Street Names:");
for (int i = 0; i < size; i++) {
System.out.println(streets[i]);
}
}

// Helper function to check if a character is a vowel


private boolean isVowel(char c) {
return "aeiou".indexOf(Character.toLowerCase(c)) != -1;
}

// Helper function to get the next vowel in cyclic sequence


private char getNextVowel(char c) {
String vowels = "aeiou";
int index = vowels.indexOf(Character.toLowerCase(c));
return vowels.charAt((index + 1) % vowels.length());
}
}

public class Init1 {


public static void main(String[] args) {
// Create an instance of the VowelsReplaced class
VowelsReplaced vr = new VowelsReplaced();
// Call the accept function to input street names from the user
vr.accept();
// Call the replaceVowels function to replace vowels in street names
vr.replaceVowels();
// Call the display function to show the shortened street names
vr.display();
}
}
VARIABLE DESCRIPTION TABLE:-

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

[Explanation: The program added up all the well-ordered two-digit numbers.


12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 34 + 35 + 36 + 37 +
38 + 39 + 45 + 46 + 47 + 48 + 49 + 56 + 57 + 58 + 59 + 67 + 68 + 69 + 78 + 79 + 89]

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];

for (int i = 1; i <= 9 - d + 1; i++) {


arr[0] = i;
sum += calcSumR(arr, 1);
}

return sum;
}

// Recursive function to generate the sum of well-ordered numbers


private static int calcSumR(int[] arr, int idx) {
if (idx == arr.length) {
int num = 0;
for (int i = 0; i < arr.length; i++) {
num = num * 10 + arr[i];
}

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.

Algorithm for searchForward function:

searchForward(word, startRow, startCol, square):


Step 1: Start of algorithm.
Step 2: Get the length of the word.
Step 3: Get the number of rows (rows) and columns (cols) in the word square.
Step 4: If (startCol + length) is greater than cols, return false (word doesn't fit in remaining
columns).
Step 5: Loop through each character index i from 0 to length - 1:
a. If the ith character of the word is not equal to the character in the word square at position
(startRow, startCol + i),
return false (mismatch at current position).
Step 6: Return true (word found in forward direction).
Step 7: End of algorithm.

Algorithm for searchBackward function:


searchBackward(word, startRow, startCol, square):
Step 1: Start of algorithm.
Step 2: Get the length of the word.
Step 3: Get the number of rows (rows) and columns (cols) in the word square.
Step 4: If (startCol - length + 1) is less than 0, return false (word doesn't fit in remaining columns).
Step 5: Loop through each character index i from 0 to length - 1:
a. If the ith character of the word is not equal to the character in the word square at position
(startRow, startCol - i),
return false (mismatch at current position).
Step 6: Return true (word found in backward direction).
Step 7: 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;

public class WordSearch {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[][] square = {
{'T', 'H', 'E', 'Q', 'T', 'T', 'E', 'P'},
{'L', 'R', 'E', 'K', 'A', 'W', 'R', 'E'},
{'T', 'S', 'E', 'T', 'N', 'O', 'C', 'I'},
{'X', 'Y', 'C', 'O', 'L', 'T', 'Z', 'J'},
{'R', 'C', 'H', 'I', 'L', 'E', 'S', 'Q'},
{'U', 'M', 'N', 'X', 'B', 'E', 'S', 'T'},
{'Y', 'X', 'K', 'O', 'O', 'C', 'Q', 'F'},
{'G', 'H', 'I', 'K', 'C', 'O', 'R', 'B'}
};

// Menu-Driven Main Function


int choice;
try{
do {
System.out.println("\nMenu:");
System.out.println("1. Search for a Word");
System.out.println("2. Exit");
System.out.print("Enter your choice (1-2): ");
choice = sc.nextInt();

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.");
}

} while (choice != 2);

sc.close();
}catch(InputMismatchException ime)
{
System.err.println(ime.getMessage());
}
}

// Function to search for a word in the word square matrix


private static void search(String word, char[][] square) {
int rows = square.length;
int cols = square[0].length;

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


for (int col = 0; col < cols; col++) {
// Check for the word in both forward and backward directions
if (searchForward(word, row, col, square)) {
System.out.println(word + ", row " + (row + 1) + ", column " + (col + 1) + ",
forwards");
return; // breaks if word is found
} else if (searchBackward(word, row, col, square)) {
System.out.println(word + ", row " + (row + 1) + ", column " + (col + 1) + ",
backwards");
return; //again, breaks if word is found
}
}
}

System.out.println("Word not found in the word square.");


}

// Function to search for a word in the forward direction


private static boolean searchForward(String word, int startRow, int startCol, char[][] square) {
int length = word.length();
int rows = square.length;
int cols = square[0].length;

if (startCol + length > cols) {


return false; // Word doesn't fit in the remaining columns
}
for (int i = 0; i < length; i++) {
if (word.charAt(i) != square[startRow][startCol + i]) {
return false; // Mismatch at current position
}
}

return true; // Word found in forward direction


}

// Function to search for a word in the backward direction


private static boolean searchBackward(String word, int startRow, int startCol, char[][] square) {
int length = word.length();
int rows = square.length;
int cols = square[0].length;

if (startCol - length + 1 < 0) {


return false; // Word doesn't fit in the remaining columns
}

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


if (word.charAt(i) != square[startRow][startCol - i]) {
return false; // Mismatch at current position
}
}

return true; // Word found in backward direction


}
}
VARIABLE DESCRIPTION TABLE:-
Variable Data
Description of Variable Scope of Variable
Name Type
sc Scanner Scanner object for input main method
8 by 8 word square matrix containing
square char[][] main method
characters
choice int User's menu choice (1 or 2) main method
main method and search
word String Word entered by the user for search
method
rows int Number of rows in the word square matrix search method
Number of columns in the word square
cols int search method
matrix
searchForward and
startRow int Starting row index for word search
searchBackward methods
searchForward and
startCol int Starting column index for word search
searchBackward methods
searchForward and
length int Length of the word being searched for
searchBackward methods
Loop variable for iteration in searchForward searchForward and
i int
and searchBackward methods searchBackward methods

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);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer N: ");
int N = sc.nextInt();
displayHS(N);
}
}
VARIABLE DESCRIPTION TABLE:-

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;

// Member Function to write stories into the file


void writeStory() {
try (PrintWriter w = new PrintWriter(new FileWriter(filename, true))) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the story paragraphs (Type 'exit' on a new line to stop):");

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.");
}
}

// Member Function to read and display the file's contents


void readStory() {
try (BufferedReader r = new BufferedReader(new FileReader(filename))) {
System.out.println("Contents of the file " + filename + ":");

String l;
while ((l = r.readLine()) != null) {
System.out.println(l);
}
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}

// Member Function to append a new story to the file


void addNewStory() {
try (PrintWriter w = new PrintWriter(new FileWriter(filename, true))) {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the new story paragraphs (Type 'exit' on a new line to stop):");

String l;
while (!(l = r.readLine()).equalsIgnoreCase("exit")) {
w.println(l);
}

System.out.println("New story added successfully.");


} catch (IOException e) {
System.out.println("Error adding the new story to the file.");
}
}

// Member Function to count the number of distinct words in the file


int countWords() {
int count = 0;

try (BufferedReader r = new BufferedReader(new FileReader(filename))) {


String l;
while ((l = r.readLine()) != null) {
boolean inWord = false;

char[] characters = l.toCharArray();


for (int i = 0; i < characters.length; i++) {
char c = characters[i];

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;
}

public static void main(String[] args) {


JatakaTales t = new JatakaTales();
Scanner sc = new Scanner (System.in);
System.out.println(" Enter new file name: ");
t.filename = sc.next();

// Menu-Driven Main Function


Scanner s = new Scanner(System.in);
int c= 0;

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;

// Member Function to write product details into the binary file


void writeDetails() {
try (DataOutputStream dout = new DataOutputStream(new FileOutputStream("product.dat",
true))) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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);

System.out.print("Do you want to add another record? (yes/no): ");


} while (br.readLine().equalsIgnoreCase("yes"));
System.out.println("Product details written to the file.");
} catch (IOException e) {
System.out.println("Error writing product details to the file.");
}
}

// Member Function to read product details from the binary file


void readDetails() {
try (DataInputStream din = new DataInputStream(new FileInputStream("product.dat"))) {
System.out.println("Product Details:");
while (din.available() > 0) {
pID = din.readUTF();
pName = din.readUTF();
pPrice = din.readFloat();
suplr = din.readUTF();
qty = din.readInt();
System.out.println("Product ID: " + pID + ", Product Name: " + pName +
", Price: " + pPrice + ", Supplier: " + suplr + ", Quantity: " + qty);
}
} catch (IOException e) {
System.out.println("Error reading product details from the file.");
}
}

// Member Function to search for a product by ID and return the details


Product search(String prodID) {
Product fP = null;
try (DataInputStream din = new DataInputStream(new FileInputStream("product.dat"))) {
while (din.available() > 0) {
pID = din.readUTF();
pName = din.readUTF();
pPrice = din.readFloat();
suplr = din.readUTF();
qty = din.readInt();
if (pID.equals(prodID)) {
fP = new Product();
fP.pID = pID;
fP.pName = pName;
fP.pPrice = pPrice;
fP.suplr = suplr;
fP.qty = qty;
break;
}
}
} catch (IOException e) {
System.out.println("Error searching for the product in the file.");
}

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.");
}
}

// Member Function to count the number of products in the file


int countProd() {
int count = 0;
try (DataInputStream din = new DataInputStream(new FileInputStream("product.dat"))) {
while (din.available() > 0) {
din.readUTF(); // Read and ignore Product ID
din.readUTF(); // Read and ignore Product Name
din.readFloat(); // Read and ignore Product Price
din.readUTF(); // Read and ignore Supplier Name
din.readInt(); // Read and ignore Quantity
count++;
}
} catch (IOException e) {
System.out.println("Error counting the number of products in the file.");
}
return count;
}
public static void main(String[] args) throws IOException
{
Product product = new Product();
// Menu-Driven Main Function
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int choice;
String searchID, updateID;
do {
System.out.println("\nMenu:");
System.out.println("1. Write Product Details\n2. Read Product Details\n3. Search Product\
n4. Update Product\n5. Count Products\n6. Exit");
System.out.print("Enter your choice (1-6): ");
choice = Integer.parseInt(br.readLine());
switch (choice) {
case 1:
product.writeDetails();
break;
case 2:
product.readDetails();
break;
case 3:
System.out.print("Enter the Product ID to search: ");
searchID = br.readLine();
Product fP = product.search(searchID);
if (fP != null) {
System.out.println("Product Found:\nProduct ID: " + fP.pID +
"\nProduct Name: " + fP.pName + "\nPrice: " + fP.pPrice +
"\nSupplier: " + fP.suplr + "\nQuantity: " + fP.qty);
} else {
System.out.println("Product not found with ID: " + searchID);
}
break;
case 4:
System.out.print("Enter the Product ID to update: ");
updateID = br.readLine();
product.updateProduct(updateID);
break;
case 5:
int count = product.countProd();
System.out.println("Number of Products in the file: " + count);
break;
case 6:
System.out.println("Exiting the program.");
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
} while (choice != 6);
}
}
VARIABLE DESCRIPTION TABLE:-

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;

try (BufferedReader reader = new BufferedReader(new FileReader("Para.txt"))) {


String line;
while ((line = reader.readLine()) != null) {
int len = line.length();
for (int i = 0; i < len; i++) {
if (line.charAt(i) == '.' || line.charAt(i) == '!' || line.charAt(i) == '?') {
sCount++;
}
}
}
} catch (IOException e) {
System.out.println("Error reading the file.");
}

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 = "";

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


char c = line.charAt(i);
if (Character.isWhitespace(c) || i == len - 1) {
if (i == len - 1) {
currWord += c;
}

if (!currWord.isEmpty()) {
wCount++;
currWord = "";
}
} else {
currWord += c;
}
}

if (wCount > mWCount) {


mWCount = wCount;
mWSentence = line;
}
}

System.out.println("Sentence with the maximum number of words:");


System.out.println(mWSentence);
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}

// Member Function to count and display the number of words starting with a vowel
static int countVowelWords() {
int vWCount = 0;

try (BufferedReader reader = new BufferedReader(new FileReader("Para.txt"))) {


String line;
while ((line = reader.readLine()) != null) {
int len = line.length();
String currWord = "";

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


char c = line.charAt(i);
if (Character.isWhitespace(c) || i == len - 1) {
if (i == len - 1) {
currWord += c;
}

if (!currWord.isEmpty() && "aeiouAEIOU".indexOf(currWord.charAt(0)) != -1) {


vWCount++;
}

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 = "";

try (BufferedReader reader = new BufferedReader(new FileReader("Para.txt"))) {


String line;
while ((line = reader.readLine()) != null) {
int len = line.length();
String currWord = "";

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


char c = line.charAt(i);
if (Character.isWhitespace(c) || i == len - 1) {
if (i == len - 1) {
currWord += c;
}

if (currWord.length() > lWord.length()) {


lWord = currWord;
lWFrequency = 1;
} else if (currWord.length() == lWord.length()) {
lWFrequency++;
}

currWord = "";
} else {
currWord += c;
}
}
}

System.out.println("Frequency of the longest word (" + lWord + "): " + lWFrequency);


} catch (IOException e) {
System.out.println("Error reading the file.");
}
}

public static void main(String[] args) throws IOException {


// Menu-Driven Main Function
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int 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));

// Accepting student details


System.out.print("Enter Student ID: ");
String studID = br.readLine();
System.out.print("Enter Student Name: ");
String sName = br.readLine();
System.out.print("Enter Marks in English: ");
int eng = Integer.parseInt(br.readLine());
System.out.print("Enter Marks in Maths: ");
int maths = Integer.parseInt(br.readLine());
System.out.print("Enter Marks in Science: ");
int sc = Integer.parseInt(br.readLine());
System.out.print("Enter Marks in Social Science: ");
int sSc = Integer.parseInt(br.readLine());

// Writing details to the file


dataOutputStream.writeUTF(studID);
dataOutputStream.writeUTF(sName);
dataOutputStream.writeInt(eng);
dataOutputStream.writeInt(maths);
dataOutputStream.writeInt(sc);
dataOutputStream.writeInt(sSc);
System.out.println("Student details written to the file.");
} catch (IOException e) {
System.out.println("Error writing student details to the file.");
}
}

// Member Function to display the contents of the binary file


static void displayContents() {
try (DataInputStream dataInputStream = new DataInputStream(new
FileInputStream("Student.bin"))) {
System.out.println("Student Details:");

while (dataInputStream.available() > 0) {


String studID = dataInputStream.readUTF();
String sName = dataInputStream.readUTF();
int eng = dataInputStream.readInt();
int maths = dataInputStream.readInt();
int sc = dataInputStream.readInt();
int sSc = dataInputStream.readInt();

System.out.println("Student ID: " + studID + ", Student Name: " + sName +


", English: " + eng + ", Maths: " + maths + ", Science: " + sc + ", Social Science: " +
sSc);
}
} catch (IOException e) {
System.out.println("Error reading student details from the file.");
}
}

// Member Function to search for a specific student by ID


static void searchStudent() {
try (DataInputStream dataInputStream = new DataInputStream(new
FileInputStream("Student.bin"))) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the Student ID to search: ");


String searchID = br.readLine();
boolean found = false;

while (dataInputStream.available() > 0) {


String studID = dataInputStream.readUTF();
String sName = dataInputStream.readUTF();
int eng = dataInputStream.readInt();
int maths = dataInputStream.readInt();
int sc = dataInputStream.readInt();
int sSc = dataInputStream.readInt();

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.");
}
}

// Member Function to edit the marks obtained in subjects for a student by ID


static void editStudentMarks() {
try {
RandomAccessFile raf = new RandomAccessFile("Student.bin", "rw");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the Student ID to edit marks: ");


String editID = br.readLine();
boolean found = false;

while (raf.getFilePointer() < raf.length()) {


String studID = raf.readUTF();
String sName = raf.readUTF();
int eng = raf.readInt();
int maths = raf.readInt();
int sc = raf.readInt();
int sSc = raf.readInt();

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());

// Move the file pointer back to update the record


raf.seek(raf.getFilePointer() - (studID.length() + sName.length() + 16));

// Update student details


raf.writeInt(eng);
raf.writeInt(maths);
raf.writeInt(sc);
raf.writeInt(sSc);

System.out.println("Marks updated successfully.");


found = true;
break;
}
}

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");

Student[] students = new Student[100]; // Assuming a maximum of 100 students


int count = 0;

while (raf.getFilePointer() < raf.length()) {


String studID = raf.readUTF();
String sName = raf.readUTF();
int eng = raf.readInt();
int maths = raf.readInt();
int sc = raf.readInt();
int sSc = raf.readInt();

students[count] = new Student(studID, sName, eng, maths, sc, sSc);


count++;
}

for (int i = 0; i < count - 1; i++) {


for (int j = 0; j < count - i - 1; j++) {
if (students[j].calculatePercentage() < students[j + 1].calculatePercentage()) {
// Swap the students
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}

System.out.println("Students in Descending Order of Percentage Marks:");


for (int i = 0; i < count; i++) {
System.out.println("Student ID: " + students[i].studID +
", Student Name: " + students[i].sName +
", Percentage: " + students[i].calculatePercentage());
}

raf.close();
} catch (IOException e) {
System.out.println("Error displaying students in descending order.");
}
}

// Member Function to remove the details of a specific student by ID


static void removeStudentDetails() {
try {
RandomAccessFile raf = new RandomAccessFile("Student.bin", "rw");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the Student ID to remove: ");


String removeID = br.readLine();
boolean found = false;

while (raf.getFilePointer() < raf.length()) {


String studID = raf.readUTF();
String sName = raf.readUTF();
int eng = raf.readInt();
int maths = raf.readInt();
int sc = raf.readInt();
int sSc = raf.readInt();
if (studID.equals(removeID)) {
// Move the file pointer back to remove the record
raf.seek(raf.getFilePointer() - (studID.length() + sName.length() + 16));

// Remove student details by overwriting with the next record


while (raf.getFilePointer() < raf.length()) {
studID = raf.readUTF();
sName = raf.readUTF();
eng = raf.readInt();
maths = raf.readInt();
sc = raf.readInt();
sSc = raf.readInt();

raf.seek(raf.getFilePointer() - (studID.length() + sName.length() + 16));


raf.writeUTF(studID);
raf.writeUTF(sName);
raf.writeInt(eng);
raf.writeInt(maths);
raf.writeInt(sc);
raf.writeInt(sSc);
}

// Truncate the file to remove the extra records


raf.setLength(raf.getFilePointer());
System.out.println("Student details removed successfully.");
found = true;
break;
}
}
if (!found) {
System.out.println("Student not found with ID: " + removeID);
}

raf.close();
} catch (IOException e) {
System.out.println("Error removing student details from the file.");
}
}

// Student Class to represent individual student records


static class Student {
String studID;
String sName;
int eng;
int maths;
int sc;
int sSc;

// 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;
}

// Member Function to calculate percentage marks


float calculatePercentage() {
return (eng + maths + sc + sSc) / 4.0f;
}
}

public static void main(String[] args) throws IOException {


// Menu-Driven Main Function
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int choice;

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.");
}

} while (choice != 7);


}
}
VARIABLE DESCRIPTION TABLE:-

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);

}
}

// Function to generate the output as specified


private static void generateOutput(String[] sentences) {
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);
}
}

// Function to count the number of vowels in a sentence


private static int countVowels(String sentence) {
int vowelCount = 0;
for (int i = 0; i < sentence.length(); i++) {

if ("aeiou".indexOf( Character.toLowerCase(sentence.charAt(i))) != -1) {


vowelCount++;
}
}
return vowelCount;
}

// Function to count the number of words in a sentence


private static int countWords(String sentence) {
String[] words = sentence.split("\\s+");
return words.length;
}
}
VARIABLE DESCRIPTION TABLE:-

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)

Class name: Multiset .

Data members/ instance variables:


integers arr[] array integer, integer size is number of elements in array.

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
}

// Member function to input integers into the multiset


void readlist() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements in the multiset: ");
int size = sc.nextInt();
System.out.println("Enter the elements of the multiset:");
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
}

// Member function to display the integers in the multiset


void displaylist() {
System.out.print("Multiset: { ");
for (int i = 0; i < arr.length && arr[i] != 0; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("}");
}

// Member function to check if the multiset is a set


int isSet() {
for (int i = 0; i < arr.length && arr[i] != 0; i++) {
for (int j = i + 1; j < arr.length && arr[j] != 0; j++) {
if (arr[i] == arr[j]) {
return 0; // Not a set
}
}
}
return 1; // Is a set
}

// Member function to convert the multiset into a set


void convert() {
for (int i = 0; i < arr.length && arr[i] != 0; i++) {
for (int j = i + 1; j < arr.length && arr[j] != 0; j++) {
if (arr[i] == arr[j]) {
// Shift elements to remove duplicates
for (int k = j; k < arr.length - 1 && arr[k] != 0; k++) {
arr[k] = arr[k + 1];
}
arr[arr.length - 1] = 0; // Set the last element to 0
j--; // Decrement j to recheck the current position
}
}
}
}
}
VARIABLE DESCRIPTION TABLE:-

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:-

You might also like