java Exam-1
java Exam-1
CSE-331
Submitted By Submitted To
Md. Shafiul Azam Md. Mahbubur Rahman
ID: 21225103132 Assistant Professor,
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;
}
} finally {
scanner.close(); // Ensure the scanner is closed
System.out.println("Transaction 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
}
}
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.");
}
}
}
}
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();
}
}