0% found this document useful (0 votes)
4 views

java Exam-1

The document outlines a series of Java programming assignments focused on exception handling, multithreading, and file operations. Each assignment includes specific tasks such as reading from files, handling exceptions, simulating bank transactions, validating email addresses, and performing matrix multiplication using threads. The document provides code examples for each task, demonstrating the implementation of error handling and multithreading concepts.

Uploaded by

smilingface4eyes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

java Exam-1

The document outlines a series of Java programming assignments focused on exception handling, multithreading, and file operations. Each assignment includes specific tasks such as reading from files, handling exceptions, simulating bank transactions, validating email addresses, and performing matrix multiplication using threads. The document provides code examples for each task, demonstrating the implementation of error handling and multithreading concepts.

Uploaded by

smilingface4eyes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Assignment

CSE-331

Submission Date: ,May 2024

Submitted By Submitted To
Md. Shafiul Azam Md. Mahbubur Rahman
ID: 21225103132 Assistant Professor,

Intake-49 Dept. CSE

Section-03 Bangladesh University of


Business and Technology
1.Write a Java program that reads data from a file named "data.txt".
Implement error handling using try-catch blocks to handle
FileNotFoundException. If the file is not found, print an error message
indicating the issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadDataFile {
public static void main(String[] args)
File file = new File("data.txt");
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.err.println("Error: The file 'data.txt' was not found.");
}
}
}

2. Write a Java program that initializes an array of integers and attempts to


access an element at an index beyond the array's length. Implement try-catch
blocks to handle the ArrayIndexOutOfBoundsException that may occur. If
the exception occurs, print a message indicating the invalid index.
import java.util.Scanner;
import java.util.Scanner;
public class ArrayAccess {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] numbers = new int[size];
System.out.println("Enter " + size + " integers:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
System.out.print("Enter the index to access: ");
int index = scanner.nextInt();
try {
int value = numbers[index];
System.out.println("Value at index " + index + " is: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Error: Attempted to access index " + index + " which
is out of bounds.");
}
} finally {
scanner.close();
}
}
}

3. Write a Java program to simulate bank account transactions. Implement


try- catch blocks to handle exceptions that may occur during withdrawal or
deposit operations, such as InsufficientFundsException for insufficient
balance and NegativeAmountException for negative amounts. Use a finally
block to ensure that resources are properly released after each transaction
import java.util.Scanner;
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class NegativeAmountException extends Exception {
public NegativeAmountException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) throws NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot deposit a negative
amount.");
}
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException,
NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot withdraw a negative
amount.");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for this
withdrawal.");
}
balance -= amount;
}

public double getBalance() {


return balance;
}
}
public class BankTransactionSimulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankAccount account = new BankAccount(1000); // Initial balance of 1000
try {
System.out.println("Initial balance: " + account.getBalance());
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
try {
account.deposit(depositAmount);
System.out.println("Deposited: " + depositAmount);
System.out.println("New balance: " + account.getBalance());
} catch (NegativeAmountException e) {
System.err.println(e.getMessage());
}
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
try {
account.withdraw(withdrawAmount);
System.out.println("Withdrew: " + withdrawAmount);
System.out.println("New balance: " + account.getBalance());
} catch (InsufficientFundsException | NegativeAmountException e) {
System.err.println(e.getMessage());
}
} finally {
scanner.close(); // Ensure the scanner is closed
System.out.println("Transaction complete. Resources released.");
}
}
}

4. Imagine you have a bank account. You can deposit and withdraw money
from your account. You should keep in mind that the total amount of money
withdrawn from your account must not exceed the total balance present in
your account. If such a scenario happens, you need to safely execute from the
banking system. Implement the above case in Java with the proper utilization
of user-defined exception mechanism.
import java.util.Scanner;
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class NegativeAmountException extends Exception {
public NegativeAmountException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) throws NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot deposit a negative
amount.");
}
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException,
NegativeAmountException {
if (amount < 0) {
throw new NegativeAmountException("Cannot withdraw a negative
amount.");
}
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for this
withdrawal.");
}
balance -= amount;
}

public double getBalance() {


return balance;
}
}
public class BankTransactionSimulation2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
BankAccount account = new BankAccount(1000); // Initial balance of 1000
try {
System.out.println("Initial balance: " + account.getBalance());
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
try {
account.deposit(depositAmount);
System.out.println("Deposited: " + depositAmount);
System.out.println("New balance: " + account.getBalance());
} catch (NegativeAmountException e) {
System.err.println(e.getMessage());
}
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();
try {
account.withdraw(withdrawAmount);
System.out.println("Withdrew: " + withdrawAmount);
System.out.println("New balance: " + account.getBalance());
} catch (InsufficientFundsException | NegativeAmountException e) {
System.err.println(e.getMessage());
}

} finally {
scanner.close(); // Ensure the scanner is closed
System.out.println("Transaction complete. Resources released.");
}
}
}

5. Write a Java program to validate an email address entered by the user.


Implement multiple catch blocks to handle different types of exceptions that
may occur during validation, such as IllegalArgumentException for invalid
format and NullPointerException for null input. Use a finally block to close
any resources opened during validation.
import java.util.Scanner;
class EmailValidator {
public static void validate(String email) throws IllegalArgumentException,
NullPointerException {
if (email == null) {
throw new NullPointerException("Email address cannot be null.");
}
String emailRegex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (!email.matches(emailRegex)) {
throw new IllegalArgumentException("Invalid email address format.");
}
}
}
public class EmailValidationProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter your email address: ");
String email = scanner.nextLine();
try {
EmailValidator.validate(email);
System.out.println("Email address is valid.");
} catch (IllegalArgumentException e) {
System.err.println("Validation Error: " + e.getMessage());
} catch (NullPointerException e) {
System.err.println("Validation Error: " + e.getMessage());
}
} finally {
scanner.close();
System.out.println("Validation complete. Resources released.");
}
}
}

6. Write a program to create four threads. Inside the first thread print your
Dept. 10 times but wait for 2 second before printing each time. Inside the
second thread print your Name 20 times. Inside the third thread print your ID
30 times. Make sure second thread gets more OS access than the first thread
and the third thread starts after finishing the second thread.
import java.util.Scanner;
class DepartmentThread extends Thread {
private String department;
public DepartmentThread(String department) {
this.department = department;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Department: " + department);
try {
Thread.sleep(2000); // Wait for 2 seconds
} catch (InterruptedException e) {
System.err.println("Department thread interrupted.");
}
}
}
}
class NameThread extends Thread {
private String name;
public NameThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("Name: " + name);
}
}
}
class IDThread extends Thread {
private String id;
private Thread dependency;
public IDThread(String id, Thread dependency) {
this.id = id;
this.dependency = dependency;
}
@Override
public void run() {
try {
dependency.join();
} catch (InterruptedException e) {
System.err.println("ID thread interrupted while waiting for dependency.");
}
for (int i = 0; i < 30; i++) {
System.out.println("ID: " + id);
}
}
}
public class ThreadExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your Department: ");
String department = scanner.nextLine();
System.out.print("Enter your Name: ");
String name = scanner.nextLine();
System.out.print("Enter your ID: ");
String id = scanner.nextLine();
DepartmentThread deptThread = new DepartmentThread(department);
NameThread nameThread = new NameThread(name);
IDThread idThread = new IDThread(id, nameThread);
nameThread.setPriority(Thread.MAX_PRIORITY);
deptThread.start();
nameThread.start();
idThread.start();
scanner.close(); // Ensure the scanner is closed
}
}

7. Write a Java program to perform matrix multiplication using


multithreading for parallel computation. Implement a method that takes two
matrices as input and computes their product using multiple threads, each
responsible for computing a portion of the result matrix. Ensure efficient
utilization of resources and minimize thread synchronization overhead.
import java.util.Scanner;
class MatrixMultiplier implements Runnable {
private int[][] result;
private int[][] matrix1;
private int[][] matrix2;
private int row;
public MatrixMultiplier(int[][] result, int[][] matrix1, int[][] matrix2, int row) {
this.result = result;
this.matrix1 = matrix1;
this.matrix2 = matrix2;
this.row = row;
}
@Override
public void run() {
int numColsMatrix2 = matrix2[0].length;
int numColsMatrix1 = matrix1[0].length;
for (int j = 0; j < numColsMatrix2; j++) {
for (int k = 0; k < numColsMatrix1; k++) {
result[row][j] += matrix1[row][k] * matrix2[k][j];
}
}
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows for Matrix 1: ");
int rowsMatrix1 = scanner.nextInt();
System.out.print("Enter number of columns for Matrix 1 / rows for Matrix 2:
");
int colsMatrix1RowsMatrix2 = scanner.nextInt();
System.out.print("Enter number of columns for Matrix 2: ");
int colsMatrix2 = scanner.nextInt();
int[][] matrix1 = new int[rowsMatrix1][colsMatrix1RowsMatrix2];
int[][] matrix2 = new int[colsMatrix1RowsMatrix2][colsMatrix2];
int[][] result = new int[rowsMatrix1][colsMatrix2];
System.out.println("Enter elements of Matrix 1:");
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < colsMatrix1RowsMatrix2; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter elements of Matrix 2:");
for (int i = 0; i < colsMatrix1RowsMatrix2; i++) {
for (int j = 0; j < colsMatrix2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}
Thread[] threads = new Thread[rowsMatrix1];
for (int i = 0; i < rowsMatrix1; i++) {
threads[i] = new Thread(new MatrixMultiplier(result, matrix1, matrix2, i));
threads[i].start();
}

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


try {
threads[i].join();
} catch (InterruptedException e) {
System.err.println("Thread interrupted: " + e.getMessage());
}
}
System.out.println("Resultant Matrix:");
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < colsMatrix2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}

8. Write a Java program to compute the factorial of a given number using


multithreading. Create two threads, one for computing the factorial of even
numbers and the other for computing the factorial of odd numbers. Combine
the results to get the final factorial.
import java.util.Scanner;
import java.math.BigInteger;
class FactorialCalculator extends Thread {
private int start;
private int end;
private int step;
private BigInteger result;
public FactorialCalculator(int start, int end, int step) {
this.start = start;
this.end = end;
this.step = step;
this.result = BigInteger.ONE;
}
public BigInteger getResult() {
return result;
}
@Override
public void run() {
for (int i = start; i <= end; i += step) {
result = result.multiply(BigInteger.valueOf(i));
}
}
}
public class FactorialMultithreading {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number to compute factorial for: ");
int n = scanner.nextInt();
BigInteger finalResult = BigInteger.ONE;
if (n < 2) {
finalResult = BigInteger.valueOf(n);
} else {
FactorialCalculator evenThread = new FactorialCalculator(2, n, 2);
FactorialCalculator oddThread = new FactorialCalculator(1, n, 2);
evenThread.start();
oddThread.start();
try {
evenThread.join();
oddThread.join();
finalResult = evenThread.getResult().multiply(oddThread.getResult());
} catch (InterruptedException e) {
System.err.println("Thread interrupted: " + e.getMessage());
}
}
System.out.println("Factorial of " + n + " is: " + finalResult);
scanner.close();
}
}

9. Write a Java program that creates two threads, one for printing uppercase
letters from A to Z and the other for printing lowercase letters from a to z.
Ensure that the letters are printed in sequence, with uppercase letters
followed by lowercase letters.
class UppercaseThread extends Thread {
@Override
public void run() {
System.out.print("Upper Case: ");
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c + " ");
try {
Thread.sleep(100); // Sleep for 100 milliseconds
} catch (InterruptedException e) {
System.err.println("Uppercase thread interrupted.");
}
}
}
}

class LowercaseThread extends Thread {


@Override
public void run() {
System.out.print("\nLower Case: ");
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c + " ");
try {
Thread.sleep(100); // Sleep for 100 milliseconds
} catch (InterruptedException e) {
System.err.println("Lowercase thread interrupted.");
}
}
}
}

public class LettersInSequence {


public static void main(String[] args) {
Thread uppercaseThread = new UppercaseThread();
Thread lowercaseThread = new LowercaseThread();

uppercaseThread.start();
try {
uppercaseThread.join(); // Ensure uppercase letters are printed first
} catch (InterruptedException e) {
System.err.println("Main thread interrupted while waiting for uppercase
thread.");
}
lowercaseThread.start();
}
}

10.Write a Java program that calculates the sum of all numbers from 1 to 100
using multiple threads. Divide the range of numbers into equal segments and
assign each thread to compute the sum of a segment. Then, combine the
results from all threads to get the final sum.
class SumCalculator extends Thread {
private int start;
private int end;
private int result;
public SumCalculator(int start, int end) {
this.start = start;
this.end = end;
this.result = 0;
}
public int getResult() {
return result;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
result += i;
}
}
}
public class MultiThreadedSum {
public static void main(String[] args) {
final int NUM_THREADS = 5;
final int NUMBERS_PER_THREAD = 100 / NUM_THREADS;
int totalSum = 0;
SumCalculator[] threads = new SumCalculator[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
int start = i * NUMBERS_PER_THREAD + 1;
int end = (i + 1) * NUMBERS_PER_THREAD;
threads[i] = new SumCalculator(start, end);
threads[i].start();
}
for (int i = 0; i < NUM_THREADS; i++) {
try {
threads[i].join();
totalSum += threads[i].getResult();
} catch (InterruptedException e) {
System.err.println("Thread interrupted: " + e.getMessage());
}
}
System.out.println("Sum of all numbers from 1 to 100: " + totalSum);
}
}

11.Write a program that takes a paragraph of text as input and counts the
occurrences of each word. Additionally, identify the five most common words
and display them along with their frequencies.
import java.util.*;
public class WordFrequencyCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a paragraph of text:");
String paragraph = scanner.nextLine();
String[] words = paragraph.split("\\s+");
Map<String, Integer> wordFreqMap = new HashMap<>();
for (String word : words) {
word = word.replaceAll("^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$", "");
word = word.toLowerCase();
wordFreqMap.put(word, wordFreqMap.getOrDefault(word, 0) + 1);
}
List<Map.Entry<String, Integer>> sortedEntries = new
ArrayList<>(wordFreqMap.entrySet());
sortedEntries.sort((entry1, entry2) ->
entry2.getValue().compareTo(entry1.getValue()));
System.out.println("\nWord Frequencies:");
for (Map.Entry<String, Integer> entry : sortedEntries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("\nTop 5 Most Common Words:");
int count = 0;
for (Map.Entry<String, Integer> entry : sortedEntries) {
if (count >= 5) {
break;
}
System.out.println(entry.getKey() + ": " + entry.getValue());
count++;
}
scanner.close();
}
}
12.Write a program that takes a sentence and a word as input and finds
whether the word is present as a substring in the sentence.
import java.util.Scanner;
public class SubStringChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
System.out.print("Enter a word to check: ");
String word = scanner.nextLine();
boolean isSubstring =
sentence.toLowerCase().contains(word.toLowerCase());
if (isSubstring) {
System.out.println("The word '" + word + "' is present as a substring in the
sentence.");
} else {
System.out.println("The word '" + word + "' is not present as a substring in
the sentence.");
}
scanner.close();
}
}

13.Write a program that takes a sentence as input and capitalizes the first
letter of each word. For example, "hello world" should become "Hello
World".
import java.util.Scanner;
public class CapitalizeWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine();
String capitalizedSentence = capitalizeFirstLetter(sentence);
System.out.println("Capitalized Sentence: " + capitalizedSentence);
scanner.close();
}
private static String capitalizeFirstLetter(String sentence) {
StringBuilder result = new StringBuilder();
boolean capitalizeNext = true;
for (char c : sentence.toCharArray()) {
if (Character.isWhitespace(c)) {
capitalizeNext = true;
} else if (capitalizeNext) {
result.append(Character.toUpperCase(c));
capitalizeNext = false;
} else {
result.append(Character.toLowerCase(c));
}
}
return result.toString();
}
}

14.Create a function that takes a sentence as input and reverses the order of
words in it. For example, "Hello world" should become "world Hello".
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence to reverse: ");
String sentence = scanner.nextLine();
scanner.close();
String reversedSentence = reverseWords(sentence);
System.out.println("Reversed Sentence: " + reversedSentence);
}
private static String reverseWords(String sentence) {
String[] words = sentence.split("\\s+");
StringBuilder reversedSentence = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedSentence.append(words[i]);
if (i > 0) {
reversedSentence.append(" ");
}
}
return reversedSentence.toString();
}
}
15.Write a program that counts the occurrences of each character in a given
string and displays the count for each character.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
scanner.close();
Map<Character, Integer> charCountMap = countCharacters(input);
displayCharacterCount(charCountMap);
}
private static Map<Character, Integer> countCharacters(String input) {
Map<Character, Integer> charCountMap = new HashMap<>();
for (char c : input.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
return charCountMap;
}
private static void displayCharacterCount(Map<Character, Integer>
charCountMap) {
System.out.println("Character Counts:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println("'" + entry.getKey() + "': " + entry.getValue());
}
}
}
16.Write a program that takes the first name and last name of a person as
input and concatenates them to form a full name.
import java.util.Scanner;
public class FullNameConcatenator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstName = scanner.nextLine();
System.out.print("Enter your last name: ");
String lastName = scanner.nextLine();
String fullName = concatenateFullName(firstName, lastName);
System.out.println("Full Name: " + fullName);
scanner.close();
}
private static String concatenateFullName(String firstName, String lastName) {
return firstName + " " + lastName;
}
}

17.Given the following strings: A = "The early bird catches the worm" B =
"Patience is a virtue" Your task is to extract the word "early" from A and
"virtue" from B. Then, concatenate these two words to form a sentence. After
that, capitalize the sentence and find the last occurrence of the letter 'V' from
the capitalized sentence. Perform all of these tasks using proper String class
functions.
public class StringManipulation {
public static void main(String[] args) {
String A = "The early bird catches the worm";
String B = "Patience is a virtue";
String wordFromA = extractWord(A, "early");
String wordFromB = extractWord(B, "virtue");
String concatenatedSentence = wordFromA + " " + wordFromB;
String capitalizedSentence = capitalizeSentence(concatenatedSentence);
int lastIndex = findLastOccurrence(capitalizedSentence, 'V');
System.out.println("Capitalized Sentence: " + capitalizedSentence);
System.out.println("Last occurrence of 'V': " + lastIndex);
}
private static String extractWord(String sentence, String word) {
int startIndex = sentence.indexOf(word);
int endIndex = startIndex + word.length();
return sentence.substring(startIndex, endIndex);
}
private static String capitalizeSentence(String sentence) {
return Character.toUpperCase(sentence.charAt(0)) + sentence.substring(1);
}
private static int findLastOccurrence(String str, char target) {
return str.lastIndexOf(target);
}
}

18.You are developing a ticket booking system for a movie theater. Design a
Java program that uses a Queue to manage ticket requests, where each
request represents a customer wanting to book a ticket. Implement methods to
add new booking requests, process bookings in the order they were received,
and display the status of ticket bookings.
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class TicketBookingSystem {
private Queue<String> ticketRequests;
public TicketBookingSystem() {
this.ticketRequests = new LinkedList<>();
}
public void addBookingRequest(String customerName) {
ticketRequests.offer(customerName);
System.out.println("Booking request added for: " + customerName);
}
public void processBookings() {
System.out.println("\nProcessing bookings:");
while (!ticketRequests.isEmpty()) {
String customerName = ticketRequests.poll();
System.out.println("Booking processed for: " + customerName);
}
}
public void displayBookingStatus() {
System.out.println("\nBooking status:");
if (ticketRequests.isEmpty()) {
System.out.println("No pending bookings.");
} else {
System.out.println("Pending bookings:");
for (String customerName : ticketRequests) {
System.out.println(customerName);
}
}
}
}
public class MovieTicketBooking {
public static void main(String[] args) {
TicketBookingSystem bookingSystem = new TicketBookingSystem();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter customer name (or type 'done' to finish): ");
String customerName = scanner.nextLine();
if (customerName.equalsIgnoreCase("done")) {
break;
}
bookingSystem.addBookingRequest(customerName);
}
scanner.close();
bookingSystem.displayBookingStatus();
bookingSystem.processBookings();
bookingSystem.displayBookingStatus();
}
}

19.Create a class named Car with properties such as price (double), brand
(String), and speed (double). These properties will be initialized when an
object of the class is created. Create five objects of the Car class and add them
to an ArrayList. Display the cars whose price is over 2000000 takas. Complete
the program
import java.util.ArrayList;
import java.util.Scanner;
class Car {
private double price;
private String brand;
private double speed;
public Car(double price, String brand, double speed) {
this.price = price;
this.brand = brand;
this.speed = speed;
}
public double getPrice() {
return price;
}
public String getBrand() {
return brand;
}
public double getSpeed() {
return speed;
}
}
public class CarDEmo {
public static void main(String[] args) {
ArrayList<Car> carList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of cars: ");
int numCars = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < numCars; i++) {
System.out.println("\nEnter details for Car " + (i + 1) + ":");
System.out.print("Price: ");
double price = scanner.nextDouble();
scanner.nextLine();
System.out.print("Brand: ");
String brand = scanner.nextLine();
System.out.print("Speed: ");
double speed = scanner.nextDouble();
scanner.nextLine();
carList.add(new Car(price, brand, speed));
}
System.out.println("\nCars with price over 2000000 takas:");
for (Car car : carList) {
if (car.getPrice() > 2000000) {
System.out.println("Brand: " + car.getBrand() + ", Price: " +
car.getPrice() + " takas, Speed: " + car.getSpeed() + " km/h");
}
}
scanner.close();
}
}

20.Write a basic Java program for managing student IDs and their grades in a
gradebook system. Implement methods to add new student IDs, remove
existing student IDs, display the list of student IDs, and store/display grades
for each student. Utilize simple data structures like arrays for storing student
IDs and grades.
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class GradebookSystem {
private ArrayList<String> studentIDs;
private ArrayList<Double> grades;
private File file;
public GradebookSystem() {
this.studentIDs = new ArrayList<>();
this.grades = new ArrayList<>();
this.file = new File("student.txt");
loadFromFile();
}
public void addStudent(String studentID, double grade) {
studentIDs.add(studentID);
grades.add(grade);
saveToFile();
System.out.println("Student ID " + studentID + " added with grade " + grade);
}
public void removeStudent(String studentID) {
int index = studentIDs.indexOf(studentID);
if (index != -1) {
studentIDs.remove(index);
grades.remove(index);
saveToFile();
System.out.println("Student ID " + studentID + " removed.");
} else {
System.out.println("Student ID " + studentID + " not found.");
}
}
public void displayStudentIDs() {
System.out.println("Student IDs:");
for (String id : studentIDs) {
System.out.println(id);
}
}
public void displayGrades() {
System.out.println("Student Grades:");
for (int i = 0; i < studentIDs.size(); i++) {
System.out.println("Student ID: " + studentIDs.get(i) + ", Grade: " +
grades.get(i));
}
}
private void loadFromFile() {
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
if (parts.length == 2) {
studentIDs.add(parts[0]);
grades.add(Double.parseDouble(parts[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("No existing gradebook file found.");
}
}
private void saveToFile() {
try (PrintWriter writer = new PrintWriter(file)) {
for (int i = 0; i < studentIDs.size(); i++) {
writer.println(studentIDs.get(i) + "," + grades.get(i));
}
} catch (FileNotFoundException e) {
System.out.println("Error saving to file.");
}
}
public static void main(String[] args) {
GradebookSystem gradebook = new GradebookSystem();
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
System.out.println("\nGradebook Menu:");
System.out.println("1. Add Student");
System.out.println("2. Remove Student");
System.out.println("3. Display Student IDs");
System.out.println("4. Display Grades");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline
switch (choice) {
case 1:
System.out.print("Enter student ID: ");
String id = scanner.nextLine();
System.out.print("Enter grade: ");
double grade = scanner.nextDouble();
scanner.nextLine(); // Consume newline
gradebook.addStudent(id, grade);
break;
case 2:
System.out.print("Enter student ID to remove: ");
String removeID = scanner.nextLine();
gradebook.removeStudent(removeID);
break;
case 3:
gradebook.displayStudentIDs();
break;
case 4:
gradebook.displayGrades();
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice. Please enter a number between 1
and 5.");
}
}

scanner.close();
}
}

21.Create a class named Student. Write a program to insert 10 Student objects in a


Stack list. Now take user input for a variable named “menu”. If menu is 1 then
insert another Student object. If menu is 2, delete the top Student object from the
stack list. If menu is 3, just output the top Student object. Use proper stack list
methods.
import java.io.*;
import java.util.Scanner;
import java.util.Stack;
class Student {
private long rollNumber;
private String name;
public Student(long rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
public long getRollNumber() {
return rollNumber;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{" +
"rollNumber=" + rollNumber +
", name='" + name + '\'' +
'}';
}
}
public class StudentStackDemo {
private static final String FILE_NAME = "student2.txt";

ublic static void main(String[] args) {


Stack<Student> studentStack = new Stack<>();
Scanner scanner = new Scanner(System.in);
loadFromFile(studentStack);
while (true) {
System.out.println("\nMenu:");
System.out.println("1. Insert another Student object");
System.out.println("2. Delete the top Student object");
System.out.println("3. Output the top Student object");
System.out.println("4. Exit");
System.out.print("Enter your choice (1-4): ");
int menu = scanner.nextInt();
switch (menu) {
case 1:
System.out.print("Enter roll number for new student: ");
long rollNumber = scanner.nextLong();
scanner.nextLine(); // Consume newline
System.out.print("Enter name for new student: ");
String name = scanner.nextLine();
studentStack.push(new Student(rollNumber, name));
saveToFile(studentStack);
System.out.println("New student added.");
break;
case 2:
if (!studentStack.isEmpty()) {
Student removedStudent = studentStack.pop();
saveToFile(studentStack);
System.out.println("Removed student: " + removedStudent);
} else {
System.out.println("Stack is empty. Cannot delete.");
}
break;
case 3:
if (!studentStack.isEmpty()) {
System.out.println("Top student: " + studentStack.peek());
} else {
System.out.println("Stack is empty.");
}
break;
case 4:
System.out.println("Exiting program.");
saveToFile(studentStack);
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please enter a number between 1
and 4.");
}
}
}
private static void loadFromFile(Stack<Student> studentStack) {
try (BufferedReader reader = new BufferedReader(new
FileReader(FILE_NAME))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
if (parts.length == 2) {
long rollNumber = Long.parseLong(parts[0]);
String name = parts[1];
studentStack.push(new Student(rollNumber, name));
}
}
System.out.println("Student information loaded from file.");
} catch (FileNotFoundException e) {
System.out.println("No existing file found. Starting with an empty stack.");
} catch (IOException e) {
System.out.println("Error reading from file.");
}
}
private static void saveToFile(Stack<Student> studentStack) {
try (PrintWriter writer = new PrintWriter(new FileWriter(FILE_NAME))) {
for (Student student : studentStack) {
writer.println(student.getRollNumber() + "," + student.getName());
}
System.out.println("Student information saved to file.");
} catch (IOException e) {
System.out.println("Error saving to file.");
}
}
}
22.Write a Java program to remove duplicates from a list of strings.
Implement a method remove duplicates that takes a List of strings as input
and removes any duplicate elements, keeping only the first occurrence of each
element.
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter strings (press Enter after each string, type 'done' to
finish):");
List<String> stringList = new ArrayList<>();
String input = scanner.nextLine();
while (!input.equals("done")) {
stringList.add(input);
input = scanner.nextLine();
}
removeDuplicates(stringList);
System.out.println("List after removing duplicates: " + stringList);
scanner.close();
}
public static void removeDuplicates(List<String> list) {
Set<String> uniqueSet = new LinkedHashSet<>(list); // Using LinkedHashSet
to maintain insertion order
list.clear(); // Clearing the original list
list.addAll(uniqueSet); // Adding unique elements back to the original list
}
}

You might also like