0% found this document useful (0 votes)
92 views18 pages

Java Ela 22mic0101 4

1. The document describes a Java programming assignment involving multi-threaded movie ticket booking. 2. The program initializes an array to represent seats, creates threads for multiple users to book seats concurrently, and displays the final seating arrangement. 3. Synchronization and locking are used to prevent multiple threads from accessing and modifying the seat array simultaneously.

Uploaded by

Varshan Manish
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)
92 views18 pages

Java Ela 22mic0101 4

1. The document describes a Java programming assignment involving multi-threaded movie ticket booking. 2. The program initializes an array to represent seats, creates threads for multiple users to book seats concurrently, and displays the final seating arrangement. 3. Synchronization and locking are used to prevent multiple threads from accessing and modifying the seat array simultaneously.

Uploaded by

Varshan Manish
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/ 18

PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

NAME: VARSHAN MANISH


REGISTRATION: 22MIC0101
PROGRAM: MTECH INTEGRATED CSE
COURSE: PROGRAMMING IN JAVA (CSI 2008)
FACULTY: DR. MANIKANDAN
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

QUESTION 1: (TEXT CAN BE COPIED; NOT AN IMAGE)


SOURCE CODE:
import java.util.concurrent.locks.ReentrantLock;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {


private static final int ROWS = 15;
private static final int COLUMNS = 15;
private static final boolean[][] seatMatrix = new boolean[ROWS][COLUMNS];
private static final ReentrantLock lock = new ReentrantLock();
private static List<Thread> userThreads = new ArrayList<>();

public static void main(String[] args) {


initializeSeatMatrix();

Runnable bookingTask = () -> {


String userName = Thread.currentThread().getName();
int[] selectedSeat = bookSeat(userName);

if (selectedSeat != null) {
System.out.println(userName + " booked seat at row " + (selectedSeat[0]
+ 1) + ", column " + (selectedSeat[1] + 1));
} else {
System.out.println(userName + " couldn't book a seat.");
}
};

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


Thread userThread = new Thread(bookingTask, "User" + (i + 1));
userThreads.add(userThread);
}

for (Thread userThread : userThreads) {


userThread.start();
}

try {
for (Thread userThread : userThreads) {
userThread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Movie booking completed.");


displaySeatMatrix();
}

private static void initializeSeatMatrix() {


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
seatMatrix[i][j] = false;
}
}
}

private static int[] bookSeat(String userName) {


PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
lock.lock();
try {
Scanner scanner = new Scanner(System.in);

int row, column;


do {
System.out.println("Enter the row and column for your seat (e.g., 3 5):
");
row = scanner.nextInt() - 1;
column = scanner.nextInt() - 1;
scanner.nextLine(); // Consume newline
} while (!isValidSeat(row, column) || seatMatrix[row][column]);

seatMatrix[row][column] = true;
return new int[]{row, column};
} finally {
lock.unlock();
}
}

private static boolean isValidSeat(int row, int column) {


return row >= 0 && row < ROWS && column >= 0 && column < COLUMNS;
}

private static void displaySeatMatrix() {


System.out.println("Final Seat Matrix:");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
if (seatMatrix[i][j]) {
System.out.print("X ");
} else {
System.out.print("O ");
}
}
System.out.println();
}
}
}

INPUT/OUTPUT:
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

QUESTION 2:
SOURCE CODE:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Customer {
private String name;
private String address;
private String accountNumber;
private double balance;
private String phoneNumber;

public Customer(String name, String address, String accountNumber, double balance,


String phoneNumber) {
this.name = name;
this.address = address;
this.accountNumber = accountNumber;
this.balance = balance;
this.phoneNumber = phoneNumber;
}
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

public String getAccountNumber() {


return accountNumber;
}

public double getBalance() {


return balance;
}

public synchronized void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited $" + amount);
notify();
} else {
System.out.println("Invalid deposit amount.");
}
}

public synchronized void withdraw(double amount) {


while (amount > balance) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

if (amount > 0) {
balance -= amount;
System.out.println("Withdrawn $" + amount);
} else {
System.out.println("Invalid withdrawal amount.");
}
}

public synchronized void viewBalance() {


System.out.println("Account Balance: $" + balance);
}
}

public class Main {


public static void main(String[] args) {
Map<String, Customer> customers = new HashMap<>();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Welcome to the Online Banking Application");
System.out.println("1. Create Customer");
System.out.println("2. View Balance");
System.out.println("3. Deposit");
System.out.println("4. Withdraw");
System.out.println("5. Exit");
System.out.print("Please select an option: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline

switch (choice) {
case 1:
System.out.print("Enter customer name: ");
String name = scanner.nextLine();
System.out.print("Enter customer address: ");
String address = scanner.nextLine();
System.out.print("Enter account number: ");
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
String accountNumber = scanner.nextLine();
System.out.print("Enter initial balance: $");
double balance = scanner.nextDouble();
scanner.nextLine(); // Consume newline
System.out.print("Enter phone number: ");
String phoneNumber = scanner.nextLine();
customers.put(accountNumber, new Customer(name, address,
accountNumber, balance, phoneNumber));
System.out.println("Customer created successfully.");
break;
case 2:
System.out.print("Enter account number: ");
String viewAccountNumber = scanner.nextLine();
Customer viewCustomer = customers.get(viewAccountNumber);
if (viewCustomer != null) {
System.out.println("Account Balance: $" +
viewCustomer.getBalance());
} else {
System.out.println("Customer not found.");
}
break;
case 3:
System.out.print("Enter account number: ");
String depositAccountNumber = scanner.nextLine();
Customer depositCustomer = customers.get(depositAccountNumber);
if (depositCustomer != null) {
System.out.print("Enter deposit amount: $");
double depositAmount = scanner.nextDouble();
depositCustomer.deposit(depositAmount);
} else {
System.out.println("Customer not found.");
}
break;
case 4:
System.out.print("Enter account number: ");
String withdrawAccountNumber = scanner.nextLine();
Customer withdrawCustomer = customers.get(withdrawAccountNumber);
if (withdrawCustomer != null) {
System.out.print("Enter withdrawal amount: $");
double withdrawAmount = scanner.nextDouble();
withdrawCustomer.withdraw(withdrawAmount);
} else {
System.out.println("Customer not found.");
}
break;
case 5:
System.out.println("Thank you for using the Online Banking
Application. Goodbye!");
System.exit(0);
default:
System.out.println("Invalid option. Please select a valid
option.");
}
}
}
}

INPUT/OUTPUT:
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

QUESTION 3:
SOURCE CODE:
public class Main {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Recruiting Company - Candidate Entry System");
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
System.out.print("Enter candidate name: ");
String name = scanner.nextLine();
System.out.print("Enter candidate phone number: ");
String phoneNumber = scanner.nextLine();
System.out.print("Enter candidate email: ");
String email = scanner.nextLine();
System.out.print("Enter one-page write-up on your field of expertise: ");
String writeUp = scanner.nextLine();

String expertise = findExpertise(writeUp);

System.out.println("Expertise Detected: " + expertise);

createCandidateFile(name, expertise, phoneNumber, name + "_" + expertise +


"_" + phoneNumber + ".txt", writeUp);

System.out.print("Do you want to enter another candidate (yes/no)? ");


String choice = scanner.nextLine().toLowerCase();
if (!choice.equals("yes")) {
break;
}
}

System.out.println("Candidate entries completed. Thank you!");


}

private static String findExpertise(String writeUp) {


if (writeUp.toLowerCase().contains("full stack")) {
return "Full Stack";
} else if (writeUp.toLowerCase().contains("artificial intelligence")) {
return "Artificial Intelligence";
} else if (writeUp.toLowerCase().contains("networking")) {
return "Networking";
} else {
return "Other";
}
}

private static void createCandidateFile(String name, String expertise, String


phoneNumber, String fileName, String writeUp) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write("Candidate Name: " + name);
writer.newLine();
writer.write("Expertise: " + expertise);
writer.newLine();
writer.write("Phone Number: " + phoneNumber);
writer.newLine();
writer.write("Email: " + phoneNumber);
writer.newLine();
writer.newLine();
writer.write("Field of Expertise Write-Up:");
writer.newLine();
writer.write(writeUp);
writer.newLine();
System.out.println("Candidate details saved in " + fileName);
} catch (IOException e) {
System.err.println("Error while creating candidate file: " +
e.getMessage());
}
}
}
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

INPUT/OUTPUT:

FILE:

QUESTION 4:

a. No, the provided class Algorithm will not compile. The reason is that the < operator
and the > operator cannot be used with generic types in this manner. In the line return
x > y ? x : y;, the compiler doesn't have enough information to compare x and y
because generic types are not guaranteed to have comparison operators defined. To
make this code compile, you would need to use a type that can be compared, such as
Comparable, and specify the generic type with an upper bound that indicates it
implements the Comparable interface.
b. public class ArrayUtils {
public static <T> void exchangeElements(T[] array, int index1, int index2) {
if (index1 < 0 || index1 >= array.length || index2 < 0 || index2 >= array.length) {
throw new IndexOutOfBoundsException("Invalid indices");
}
T temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

public static void main(String[] args) {


Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"apple", "banana", "cherry", "date", "elderberry"};

// Exchange two elements in an integer array


exchangeElements(intArray, 1, 3);

// Exchange two elements in a string array


exchangeElements(strArray, 0, 4);

// Print the updated arrays


for (Integer num : intArray) {
System.out.print(num + " ");
}
System.out.println();

for (String fruit : strArray) {


System.out.print(fruit + " ");
}
}
c. Generics in Java offer a range of benefits despite the fact that type parameters are
erased at compile time. Some of the key advantages of using generics include:
Type Safety: Generics provide type safety by allowing you to specify the expected data
type for a collection, class, or method. This helps prevent type-related errors at compile
time and avoids the need for runtime type casting, which can lead to runtime exceptions
and reduce code robustness.
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

Code Clarity: Generics improve code readability and maintainability by expressing the
intended types in the code. This makes the code more self-documenting and
understandable to developers, as the types are explicitly stated.

Code Reusability: Generics enable you to write generic classes and methods that work
with different data types. This promotes code reusability and reduces code duplication, as
the same logic can be applied to various data types.
d. After type erasure, the Pair class will be transformed by replacing the type parameters
K and V with their respective bounds, which are Object since they are not bounded.
Here's the class after type erasure:
public class Pair {
public Pair(Object key, Object value) {
this.key = key;
this.value = value;
}

public Object getKey() {


return key;
}

public Object getValue() {


return value;
}

public void setKey(Object key) {


this.key = key;
}

public void setValue(Object value) {


this.value = value;
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

private Object key;


private Object value;
}
In the erasure process, the type parameters K and V are replaced with Object. This means
that the class Pair can store any type of object for both key and value. While type erasure
allows for backward compatibility with non-generic code, it loses some of the type-specific
benefits of generics, such as compile-time type checking.

QUESTION 5:
SOURCE CODE:
import java.util.HashMap;
import java.util.Map;

public class Main {


public static void main(String[] args) {
String paragraph = "Hello world, this is a sample paragraph. " +
"It contains several words starting with A, such as apple and apricot.
" +
"The sun is shining, and the birds are singing. " +
"This paragraph contains the word apple multiple times.";

int wordsStartingWithA = countWordsStartingWithA(paragraph);

String replacedParagraph = replaceWordsContainingIs(paragraph);

Map<String, Integer> wordCount = countWordOccurrences(paragraph);

String capitalizedParagraph = capitalizeFirstLetter(paragraph);

boolean containsWordWorld = containsWordIgnoreCase(paragraph, "wOrLd");

System.out.println("Words starting with 'A': " + wordsStartingWithA);


System.out.println("After replacing 'is' with 'are':");
System.out.println(replacedParagraph);
System.out.println("Word count:");
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("Capitalized paragraph:");
System.out.println(capitalizedParagraph);
System.out.println("Contains 'wOrLd' (case-insensitive): " +
containsWordWorld);
}

public static int countWordsStartingWithA(String paragraph) {


String[] words = paragraph.split("\\s+");
int count = 0;
for (String word : words) {
if (word.matches("[Aa][a-zA-Z]*")) {
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
count++;
}
}
return count;
}

public static String replaceWordsContainingIs(String paragraph) {


return paragraph.replaceAll("\\bis\\b", "are");
}

public static Map<String, Integer> countWordOccurrences(String paragraph) {


String[] words = paragraph.split("\\s+");
Map<String, Integer> wordCount = new HashMap<>();
for (String word : words) {
word = word.toLowerCase();
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
return wordCount;
}

public static String capitalizeFirstLetter(String paragraph) {


String[] words = paragraph.split("\\s+");
StringBuilder result = new StringBuilder();
for (String word : words) {
if (!word.isEmpty()) {
char firstChar = Character.toUpperCase(word.charAt(0));
String restOfWord = word.substring(1);
result.append(firstChar).append(restOfWord);
}
result.append(" ");
}
return result.toString().trim();
}

public static boolean containsWordIgnoreCase(String paragraph, String wordToFind) {


return paragraph.toLowerCase().contains(wordToFind.toLowerCase());
}
}

INPUT/OUTPUT:
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4
PROGRAMMING IN JAVA ELA DIGITAL ASSIGNMENT 4

You might also like