1) Food-Ordering-System class ItemNotFoundException extends Exception {
import java.util.*; public ItemNotFoundException(String msg) {
super(msg);
// Base class for food items }
class FoodItem { }
String name;
int price; class InvalidQuantityException extends Exception {
public InvalidQuantityException(String msg) {
public FoodItem(String name, int price) { super(msg);
this.name = name; }
this.price = price; }
}
class Order {
public void displayInfo() { static double dailyTotal = 0;
System.out.println("Food Item: " + name + ",
Price: ₹" + price); public void processOrder(List<FoodItem> menu,
} Customer customer)
} throws ItemNotFoundException,
InvalidQuantityException {
class MainCourse extends FoodItem { if (customer.quantity <= 0)
MainCourse(String name, int price) { throw new InvalidQuantityException("Invalid
super(name, price); quantity: " + customer.quantity);
} boolean found = false;
for (FoodItem item : menu) {
public void displayInfo() { if
System.out.println("Main Course: " + name + ", (item.name.equalsIgnoreCase(customer.ordered)) {
Price: ₹" + price); found = true;
} int subtotal = customer.quantity *
} item.price;
System.out.println("Order: " + item.name +
class Dessert extends FoodItem { ", Price: ₹" + item.price + ", Quantity: " +
Dessert(String name, int price) { customer.quantity);
super(name, price); System.out.println("Subtotal: ₹" + subtotal);
} double withGST = subtotal + (subtotal *
0.18);
public void displayInfo() { double withService = withGST + (withGST *
System.out.println("Dessert: " + name + ", Price: 0.08);
₹" + price); System.out.printf("Total with GST: ₹%.2f\n",
} withGST);
} System.out.printf("Total with Service
Charge: ₹%.2f\n\n", withService);
class Beverage extends FoodItem { dailyTotal += withService;
Beverage(String name, int price) { return;
super(name, price); }
} }
if (!found) throw new
public void displayInfo() { ItemNotFoundException("Item '" + customer.ordered
System.out.println("Beverage: " + name + ", + "' not found in the menu.");
Price: ₹" + price); }
}
} public void displayDailyTotal() {
System.out.printf("Total Sales for the Day: ₹
class Customer { %.2f\n", dailyTotal);
String ordered; }
int quantity; }
public Customer(String ordered, int quantity) { public class FinalFoodOrderingApp {
this.ordered = ordered; public static void main(String[] args) {
this.quantity = quantity; Scanner sc = new Scanner(System.in);
} List<FoodItem> menu = new ArrayList<>();
} menu.add(new MainCourse("Pizza", 200));
menu.add(new Dessert("IceCream", 100));
menu.add(new Beverage("Coke", 50)); // Base class for all vehicles
class Vehicle {
System.out.println("----- MENU -----"); String type; double cost; int time;
for (FoodItem item : menu) { Vehicle(String type, double cost, int time) {
item.displayInfo(); this.type = type; this.cost = cost; this.time =
} time;
}
Order order = new Order(); void displayServiceDetails() {
boolean ordering = true; System.out.println("TYPE: " + type);
System.out.println("Cost: ₹" + cost);
while (ordering) { System.out.println("Duration: " + time + "
System.out.println("\nChoose an option:"); hours\n");
System.out.println("1. Order Pizza"); }
System.out.println("2. Order IceCream"); }
System.out.println("3. Order Coke");
System.out.println("4. Exit"); class Bike extends Vehicle {
Bike(String type, double cost, int time)
int choice = sc.nextInt(); { super(type, cost, time); }
sc.nextLine(); // consume newline void displayServiceDetails() {
String foodName = ""; System.out.println("Bike Service Details:");
switch (choice) { super.displayServiceDetails();
case 1: }
foodName = "Pizza"; }
break;
case 2: class Car extends Vehicle {
foodName = "IceCream"; Car(String type, double cost, int time)
break; { super(type, cost, time); }
case 3: void displayServiceDetails() {
foodName = "Coke"; System.out.println("Car Service Details:");
break; super.displayServiceDetails();
case 4: }
ordering = false; }
continue;
default: class Truck extends Vehicle {
System.out.println("Invalid choice. Try Truck(String type, double cost, int time)
again."); { super(type, cost, time); }
continue; void displayServiceDetails() {
} System.out.println("Truck Service Details:");
super.displayServiceDetails();
System.out.print("Enter quantity for " + }
foodName + ": "); }
int qty = sc.nextInt();
sc.nextLine(); // consume newline class InvalidVehicleTypeException extends Exception
Customer customer = new {
Customer(foodName, qty); public InvalidVehicleTypeException(String msg)
{ super(msg); }
try { }
order.processOrder(menu, customer);
} catch (ItemNotFoundException | class DuplicateBookingException extends Exception {
InvalidQuantityException e) { public DuplicateBookingException(String msg)
System.out.println("ERROR: " + { super(msg); }
e.getMessage()); }
}
} class TotalBill {
double calculateTotal(List<Vehicle> vehicles) {
order.displayDailyTotal(); double total = 0;
sc.close(); for (Vehicle v : vehicles) total += v.cost;
} return total;
} }
2) Vehicle-Management-System }
import java.util.*;
public class VeMain {
public static void main(String[] args) { break;
Scanner sc = new Scanner(System.in);
List<Vehicle> vehicleList = new ArrayList<>(); case 4:
Set<String> bookedTypes = new HashSet<>(); System.out.println("Exiting...");
return;
while (true) {
System.out.println("\n1. Book Vehicle"); default:
System.out.println("2. Show All Bookings"); System.out.println("Invalid choice.\n");
System.out.println("3. Show Total Income"); }
System.out.println("4. Exit"); }
System.out.print("Enter your choice: "); }
int ch = sc.nextInt(); }
sc.nextLine(); // consume newline 3) Course-Registration-System
import java.util.*;
switch (ch) {
case 1: class Student {
System.out.print("Enter Vehicle Type String name;
(Bike/Car/Truck): "); Student(String name) {
String type = sc.nextLine(); this.name = name;
}
try { }
if (!Arrays.asList("Bike", "Car",
"Truck").contains(type)) class Course {
throw new String name;
InvalidVehicleTypeException("Invalid vehicle type: " int maxCapacity;
+ type); int enrolled;
if (!bookedTypes.add(type)) List<String> registeredStudents = new
throw new ArrayList<>();
DuplicateBookingException("Duplicate booking for: " Course(String name, int maxCapacity, int enrolled)
+ type); {
this.name = name;
switch (type) { this.maxCapacity = maxCapacity;
case "Bike": vehicleList.add(new this.enrolled = enrolled;
Bike("Bike", 100, 5)); break; }
case "Car": vehicleList.add(new }
Car("Car", 1000, 10)); break;
case "Truck": vehicleList.add(new class Core extends Course {
Truck("Truck", 10000, 15)); break; static int coreCount = 0;
} Core(String name, int maxCapacity, int enrolled) {
super(name, maxCapacity, enrolled);
System.out.println(type + " booked coreCount += enrolled;
successfully!\n"); }
} catch (Exception e) { }
System.out.println("ERROR: " +
e.getMessage() + "\n"); class Elective extends Course {
} static int electiveCount = 0;
break; Elective(String name, int maxCapacity, int
enrolled) {
case 2: super(name, maxCapacity, enrolled);
if (vehicleList.isEmpty()) { electiveCount += enrolled;
System.out.println("No bookings yet.\ }
n"); }
} else {
for (Vehicle v : vehicleList) class Audit extends Course {
v.displayServiceDetails(); static int auditCount = 0;
} Audit(String name, int maxCapacity, int enrolled) {
break; super(name, maxCapacity, enrolled);
auditCount += enrolled;
case 3: }
TotalBill bill = new TotalBill(); }
System.out.println("Total Income for the
Day: ₹" + bill.calculateTotal(vehicleList)); class CapacityFullException extends Exception {
public CapacityFullException(String msg) { System.out.println("Select Course: 1-
super(msg); Core101 2-Elective202 3-Audit303");
} int courseChoice = sc.nextInt();
} Course selectedCourse = null;
class PrerequisiteNotMetException extends if (courseChoice == 1) selectedCourse =
Exception { c1;
public PrerequisiteNotMetException(String msg) { else if (courseChoice == 2)
super(msg); selectedCourse = c2;
} else if (courseChoice == 3)
} selectedCourse = c3;
else {
class Registration { System.out.println("Invalid Course.");
public void register(Student s, Course c, boolean break;
prerequisiteMet) throws CapacityFullException, }
PrerequisiteNotMetException {
if (!prerequisiteMet) System.out.print("Prerequisite met?
throw new (true/false): ");
PrerequisiteNotMetException("Prerequisite not met boolean pre = sc.nextBoolean();
for " + s.name + " in " + c.name);
if (c.enrolled < c.maxCapacity) { try {
c.enrolled++; reg.register(s, selectedCourse, pre);
c.registeredStudents.add(s.name); } catch (Exception e) {
if (c instanceof Core) Core.coreCount++; System.out.println("Exception: " +
else if (c instanceof Elective) e.getMessage());
Elective.electiveCount++; }
else if (c instanceof Audit) Audit.auditCount+ break;
+;
System.out.println(s.name + " registered for " case 2:
+ c.name); System.out.println("\nCourse
} else { Registrations:");
throw new CapacityFullException("Course '" + System.out.println(c1.name + ": " +
c.name + "' is full for " + s.name); c1.registeredStudents);
} System.out.println(c2.name + ": " +
} c2.registeredStudents);
} System.out.println(c3.name + ": " +
c3.registeredStudents);
public class Mainclass { break;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); case 3:
Registration reg = new Registration(); System.out.println("\nTotal Students
Registered:");
Course c1 = new Core("Core101", 5, 2); System.out.println("Core: " +
Course c2 = new Elective("Elective202", 5, 5); Core.coreCount);
Course c3 = new Audit("Audit303", 5, 4); System.out.println("Elective: " +
Elective.electiveCount);
while (true) { System.out.println("Audit: " +
System.out.println("\n1. Register Student"); Audit.auditCount);
System.out.println("2. Show Registrations"); break;
System.out.println("3. Show Total Counts");
System.out.println("4. Exit"); case 4:
System.out.print("Enter choice: "); System.out.println("Exiting...");
int choice = sc.nextInt(); return;
sc.nextLine(); // consume newline
default:
switch (choice) { System.out.println("Invalid Choice.");
case 1: }
System.out.print("Enter Student Name: }
"); }
String name = sc.nextLine(); }
Student s = new Student(name); 4) Library-Management-System
import java.util.*;
// Base Book Class // Custom Exceptions
abstract class Book { class OverdueReturnException extends Exception {
String name; OverdueReturnException(String message) {
boolean isAvailable = true; super(message);
}
Book(String name) { }
this.name = name;
} class BorrowLimitExceededException extends
} Exception {
BorrowLimitExceededException(String message) {
class ReferenceBook extends Book { super(message);
ReferenceBook(String name) { }
super(name); }
}
} class BookNotAvailableException extends Exception {
BookNotAvailableException(String message) {
class TextBook extends Book { super(message);
TextBook(String name) { }
super(name); }
}
} // Library class
class Library {
class Journal extends Book { List<Book> books = new ArrayList<>();
Journal(String name) { double totalFinesCollected = 0;
super(name);
} void addBook(Book book) {
} books.add(book);
}
// Member base class
abstract class Member { Book findBook(String name) {
String name; for (Book book : books) {
List<Book> borrowedBooks = new ArrayList<>(); if (book.name.equalsIgnoreCase(name))
return book;
Member(String name) { }
this.name = name; return null;
} }
abstract int getBorrowLimit(); void borrowBook(Book book, Member member)
} throws BookNotAvailableException,
BorrowLimitExceededException {
class Student extends Member { if (!book.isAvailable) {
Student(String name) { throw new BookNotAvailableException("Book
super(name); '" + book.name + "' is not available.");
} }
if (member.borrowedBooks.size() >=
@Override member.getBorrowLimit()) {
int getBorrowLimit() { throw new
return 3; BorrowLimitExceededException(member.name + "
} has exceeded the borrow limit.");
} }
class Faculty extends Member { book.isAvailable = false;
Faculty(String name) { member.borrowedBooks.add(book);
super(name); System.out.println(member.name + "
} successfully borrowed '" + book.name + "'");
}
@Override
int getBorrowLimit() { void returnBook(Book book, Member member,
return 5; boolean isLate) throws OverdueReturnException {
} if (!member.borrowedBooks.contains(book)) {
}
System.out.println("Book '" + book.name + "' boolean running = true;
was not borrowed by " + member.name); while (running) {
return; System.out.println("\nMenu:");
} System.out.println("1. Borrow Book");
System.out.println("2. Return Book");
member.borrowedBooks.remove(book); System.out.println("3. View Total Fines");
book.isAvailable = true; System.out.println("4. Exit");
System.out.println("5. Display Books");
if (isLate) { System.out.print("Choose an option: ");
double fine = 100.0; int choice = sc.nextInt();
totalFinesCollected += fine; sc.nextLine(); // consume newline
throw new OverdueReturnException(
"Book '" + book.name + "' returned late switch (choice) {
by " + member.name + ". Fine: ₹" + fine); case 1:
} else { System.out.print("Enter book name to
System.out.println(member.name + " borrow: ");
returned '" + book.name + "' on time."); String borrowName = sc.nextLine();
} Book bookToBorrow =
} library.findBook(borrowName);
if (bookToBorrow == null) {
void showTotalFines() { System.out.println("Book not found.");
System.out.println("Total fines collected today: break;
₹" + totalFinesCollected); }
} try {
library.borrowBook(bookToBorrow,
void displayBooks() { member);
System.out.println("\nAvailable Books in } catch (Exception e) {
Library:"); System.out.println("Error: " +
for (Book book : books) { e.getMessage());
String status = book.isAvailable ? "Available" : }
"Borrowed"; break;
System.out.println("- " + book.name + " [" +
book.getClass().getSimpleName() + "] - " + status); case 2:
} System.out.print("Enter book name to
} return: ");
} String returnName = sc.nextLine();
Book bookToReturn =
// Main class with switch input library.findBook(returnName);
public class Lib { if (bookToReturn == null) {
public static void main(String[] args) { System.out.println("Book not found.");
Scanner sc = new Scanner(System.in); break;
Library library = new Library(); }
System.out.print("Was the return late?
// Add sample books (Y/N): ");
library.addBook(new ReferenceBook("Ref- String late = sc.nextLine();
101")); boolean isLate =
library.addBook(new TextBook("Text-202")); late.equalsIgnoreCase("Y");
library.addBook(new Journal("Journal-303")); try {
library.returnBook(bookToReturn,
// Choose member type member, isLate);
System.out.print("Enter your name: "); } catch (OverdueReturnException e) {
String memberName = sc.nextLine(); System.out.println("Exception: " +
System.out.print("Are you a Student or Faculty? e.getMessage());
(S/F): "); }
String type = sc.nextLine(); break;
Member member;
if (type.equalsIgnoreCase("F")) { case 3:
member = new Faculty(memberName); library.showTotalFines();
} else { break;
member = new Student(memberName);
} case 4:
running = false;
System.out.println("Exiting system."); }
break;
public abstract void displayInfo();
case 5: }
library.displayBooks();
break; // Doctor class
class Doctor extends Person {
default: private String specialization;
System.out.println("Invalid option. Try private List<Integer> availableSlots;
again."); private Set<Integer> bookedSlots = new
} HashSet<>();
} private int consultationFee;
sc.close(); Doctor(String name, int age, String id, String
} specialization, List<Integer> slots, int fee) {
} super(name, age, id);
5) Hospital-Management-System this.specialization = specialization;
import java.util.*; this.availableSlots = slots;
this.consultationFee = fee;
// Custom Exceptions }
class AppointmentException extends Exception {
AppointmentException(String message) { public void displayInfo() {
super(message); System.out.println(
} getName() + " | " + specialization + " | Fee:
} $" + consultationFee + " | Available: " +
availableSlots);
class InvalidPatientException extends Exception { }
InvalidPatientException(String message) {
super(message); public boolean isAvailableAt(int hour) {
} return availableSlots.contains(hour) && !
} bookedSlots.contains(hour);
}
class InvalidInputException extends Exception {
InvalidInputException(String message) { public void book(int hour) {
super(message); bookedSlots.add(hour);
} }
}
public int getConsultationFee() {
class BudgetExceededException extends Exception { return consultationFee;
BudgetExceededException(String message) { }
super(message);
} public String getSpecialization() {
} return specialization;
}
// Base Person class }
abstract class Person {
private String name; // Patient class
private int age; class Patient extends Person {
private String id; private String disease;
private int budget;
Person(String name, int age, String id) {
this.name = name; Patient(String name, int age, String id, String
this.age = age; disease, int budget) {
this.id = id; super(name, age, id);
} this.disease = disease;
this.budget = budget;
public String getName() { }
return name;
} public void displayInfo() {
System.out.println("Patient: " + getName() + ",
public String getId() { Disease: " + disease + ", Budget: $" + budget);
return id; }
if (d.contains("skin") || d.contains("rash"))
public String getDisease() { return "Dermatologist";
return disease; if (d.contains("fever") || d.contains("cold"))
} return "General Physician";
throw new InvalidInputException("No specialist
public int getBudget() { found for this disease.");
return budget; }
} }
}
// Main system with menu and switch
// Appointment class public class HospitalSystem {
class Appointment { public static void main(String[] args) {
private Doctor doctor; Scanner sc = new Scanner(System.in);
private Patient patient; List<Appointment> appointmentHistory = new
private int hour; ArrayList<>();
Appointment(Doctor doctor, Patient patient, int Doctor[] doctors = {
hour) new Doctor("Dr. Smith", 45, "D101",
throws AppointmentException, "Cardiologist", Arrays.asList(10, 11, 17, 18), 1000),
InvalidPatientException, BudgetExceededException { new Doctor("Dr. Patel", 50, "D102",
if (patient.getId() == null || "Orthopedic", Arrays.asList(9, 10, 16, 17), 800),
patient.getId().isEmpty()) { new Doctor("Dr. Mehta", 38, "D103",
throw new InvalidPatientException("Patient ID "Dermatologist", Arrays.asList(14, 15, 18, 19), 600),
is required."); new Doctor("Dr. Roy", 40, "D104", "General
} Physician", Arrays.asList(8, 9, 18, 19), 500)
if (!doctor.isAvailableAt(hour)) { };
throw new AppointmentException("Doctor is
not available at this time or already booked."); boolean running = true;
}
if (doctor.getConsultationFee() > while (running) {
patient.getBudget()) { System.out.println("\n===== Hospital
throw new Appointment System =====");
BudgetExceededException("Doctor's fee exceeds System.out.println("1. Book an
your budget."); Appointment");
} System.out.println("2. View Booked
doctor.book(hour); Appointments");
this.doctor = doctor; System.out.println("3. Exit");
this.patient = patient; System.out.print("Enter your choice: ");
this.hour = hour; int choice = sc.nextInt();
System.out.println("Appointment confirmed at " sc.nextLine(); // consume newline
+ hour + ":00 with Dr. " + doctor.getName()
+ " (" + doctor.getSpecialization() + ") for $" switch (choice) {
+ doctor.getConsultationFee()); case 1:
} try {
System.out.print("Enter patient name:
public void displayAppointment() { ");
System.out.println("Dr. " + doctor.getName() + " String name = sc.nextLine();
with " + patient.getName() + System.out.print("Enter age: ");
" at " + hour + ":00 | Fee: $" + int age = sc.nextInt();
doctor.getConsultationFee()); sc.nextLine();
} System.out.print("Enter patient ID: ");
} String id = sc.nextLine();
System.out.print("Enter your disease
// Disease-specialist mapping (e.g., fever, rash, heart, skin, bones, cold): ");
class DiseaseSpecialistMapper { String disease = sc.nextLine();
public static String getSpecialist(String disease) System.out.print("Enter your budget
throws InvalidInputException { ($): ");
String d = disease.toLowerCase(); int budget = sc.nextInt();
if (d.contains("heart")) sc.nextLine();
return "Cardiologist";
if (d.contains("bone")) Patient patient = new Patient(name,
return "Orthopedic"; age, id, disease, budget);
patient.displayInfo(); System.out.println("Unexpected error
occurred.");
String specialist = }
DiseaseSpecialistMapper.getSpecialist(disease); break;
System.out.println("\nYou need a: " +
specialist); case 2:
System.out.println("\n--- Booked
List<Doctor> availableDoctors = new Appointments ---");
ArrayList<>(); if (appointmentHistory.isEmpty()) {
for (Doctor doc : doctors) { System.out.println("No appointments
if booked yet.");
(doc.getSpecialization().equalsIgnoreCase(specialist) } else {
){ for (int i = 0; i <
availableDoctors.add(doc); appointmentHistory.size(); i++) {
} System.out.print((i + 1) + ". ");
}
appointmentHistory.get(i).displayAppointment();
if (availableDoctors.isEmpty()) { }
throw new }
AppointmentException("No doctors available for this break;
specialization.");
} case 3:
running = false;
System.out.println("\nAvailable System.out.println("Thank you for using
Doctors:"); the Hospital Appointment System.");
for (int i = 0; i < availableDoctors.size(); break;
i++) {
System.out.print((i + 1) + ". "); default:
availableDoctors.get(i).displayInfo(); System.out.println("Invalid choice. Please
} try again.");
}
System.out.print("Choose doctor }
number: ");
int docIndex = sc.nextInt() - 1; sc.close();
if (docIndex < 0 || docIndex >= }
availableDoctors.size()) { }
throw new 6) Shopping-System
InvalidInputException("Invalid doctor selection."); import java.util.*;
}
class Product {
Doctor selectedDoctor = private int id;
availableDoctors.get(docIndex); private String name;
System.out.print("Enter desired private double price;
appointment hour (0–23): "); private String category;
int hour = sc.nextInt();
public Product(int id, String name, double price,
if (hour < 0 || hour > 23) { String category) {
throw new this.id = id;
InvalidInputException("Invalid time. Enter hour this.name = name;
between 0–23."); this.price = price;
} this.category = category;
}
Appointment appt = new
Appointment(selectedDoctor, patient, hour); public int getId() { return id; }
appointmentHistory.add(appt); public String getName() { return name; }
public double getPrice() { return price; }
} catch (InvalidInputException | public String getCategory() { return category; }
AppointmentException | InvalidPatientException | }
BudgetExceededException e) {
System.out.println("Error: " + class CartItem {
e.getMessage()); private Product product;
} catch (Exception e) { private int quantity;
}
public CartItem(Product product, int quantity) { }
this.product = product;
this.quantity = quantity; class ProductNotFoundException extends Exception {
} public ProductNotFoundException(String
message) {
public Product getProduct() { return product; } super(message);
public int getQuantity() { return quantity; } }
public double getSubtotal() { }
return product.getPrice() * quantity;
} public class ShoppingSystemWithBudget {
} public static Set<String>
getCategories(List<Product> products) {
class ShoppingCart { Set<String> categories = new
private List<CartItem> items = new ArrayList<>(); LinkedHashSet<>();
private final double GST_RATE = 0.18; for (Product p : products) {
categories.add(p.getCategory());
public void addItem(Product product, int quantity) }
{ return categories;
items.add(new CartItem(product, quantity)); }
}
public static void
public double getSubtotal() { displayProductsByCategory(List<Product> products,
double subtotal = 0; String category) {
for (CartItem item : items) { System.out.println("\n--- " + category + "
subtotal += item.getSubtotal(); Products ---");
} for (Product p : products) {
return subtotal; if
} (p.getCategory().equalsIgnoreCase(category)) {
System.out.printf("ID: %d | %s - $%.2f\n",
public double getGstAmount() { p.getId(), p.getName(), p.getPrice());
return getSubtotal() * GST_RATE; }
} }
}
public double getTotalWithGst() {
return getSubtotal() + getGstAmount(); public static Product getProductById(List<Product>
} products, int id) throws ProductNotFoundException {
for (Product p : products) {
public void viewCart() { if (p.getId() == id)
if (items.isEmpty()) { return p;
System.out.println("Your cart is empty."); }
return; throw new
} ProductNotFoundException("Product with ID " + id +
" not found.");
System.out.println("\n--- Shopping Cart ---"); }
for (CartItem item : items) {
Product p = item.getProduct(); public static void main(String[] args) {
System.out.printf("%s x %d = $%.2f\n", Scanner sc = new Scanner(System.in);
p.getName(), item.getQuantity(),
item.getSubtotal()); // Sample product list
} List<Product> products = new ArrayList<>();
products.add(new Product(1, "Laptop", 999.99,
double subtotal = getSubtotal(); "Electronics"));
double gst = getGstAmount(); products.add(new Product(2, "Smartphone",
double total = getTotalWithGst(); 599.99, "Electronics"));
System.out.printf("Subtotal: $%.2f\n", subtotal); products.add(new Product(3, "Headphones",
System.out.printf("GST (18%%): $%.2f\n", gst); 199.99, "Electronics"));
System.out.printf("Total: $%.2f\n", total); products.add(new Product(4, "T-Shirt", 29.99,
} "Clothing"));
products.add(new Product(5, "Jeans", 49.99,
public boolean isEmpty() { "Clothing"));
return items.isEmpty();
products.add(new Product(6, "Sneakers", 89.99, break;
"Clothing"));
products.add(new Product(7, "Fiction Book", case 2:
14.99, "Books")); System.out.println("\nEnter category to
products.add(new Product(8, "Notebook", 5.99, view products:");
"Books")); String selectedCategory =
sc.nextLine().trim();
ShoppingCart cart = new ShoppingCart(); if (!
double budget = 0; getCategories(products).contains(selectedCategory))
{
// Get user budget System.out.println("Invalid category.");
while (true) { break;
try { }
System.out.print("Enter your shopping
budget: $"); displayProductsByCategory(products,
budget = sc.nextDouble(); selectedCategory);
if (budget <= 0) throw new
IllegalArgumentException("Budget must be greater try {
than 0."); System.out.print("Enter product ID: ");
sc.nextLine(); // clear buffer int id = sc.nextInt();
break; Product product =
} catch (InputMismatchException e) { getProductById(products, id);
System.out.println("Please enter a valid sc.nextLine(); // consume newline
number.");
sc.nextLine(); if (!
} catch (IllegalArgumentException e) { product.getCategory().equalsIgnoreCase(selectedCat
System.out.println(e.getMessage()); egory)) {
sc.nextLine(); System.out.println("Product not in
} selected category.");
} break;
}
boolean running = true;
while (running) { System.out.print("Enter quantity: ");
// Menu int qty = sc.nextInt();
System.out.println("\n=== Shopping Menu sc.nextLine();
==="); if (qty <= 0) throw new
System.out.println("1. View Categories"); IllegalArgumentException("Quantity must be greater
System.out.println("2. Add Product to Cart"); than 0.");
System.out.println("3. View Cart");
System.out.println("4. Checkout & Budget cart.addItem(product, qty);
Check"); System.out.println("Added to cart: " +
System.out.println("5. Exit"); qty + " x " + product.getName());
System.out.print("Enter choice: ");
} catch (ProductNotFoundException e) {
int choice = -1; System.out.println("Error: " +
try { e.getMessage());
choice = sc.nextInt(); sc.nextLine();
sc.nextLine(); // consume newline } catch (InputMismatchException e) {
} catch (InputMismatchException e) { System.out.println("Invalid input.");
System.out.println("Invalid input. Please sc.nextLine();
enter a number."); } catch (IllegalArgumentException e) {
sc.nextLine(); System.out.println("Error: " +
continue; e.getMessage());
} sc.nextLine();
}
switch (choice) { break;
case 1:
System.out.println("\n--- Available case 3:
Categories ---"); cart.viewCart();
for (String cat : getCategories(products)) { break;
System.out.println("- " + cat);
} case 4:
cart.viewCart(); int idx = seat - 1;
double total = cart.getTotalWithGst(); booked[idx] = true;
System.out.println("\n--- Budget Check customerNames[idx] = customerName;}
---"); revenue += ticketPrice * seats.size();
if (total <= budget) { System.out.printf("Seats %s booked for %s.
System.out.printf("Your total $%.2f is Please pay $%.2f\n", seats, customerName,
within your budget of $%.2f.\n", total, budget); ticketPrice * seats.size());}
} else { public void cancelSeat(int seat, String
System.out.printf("Your total $%.2f customerName) throws InvalidSeatException {
exceeds your budget of $%.2f.\n", total, budget); validateSeat(seat);
} int idx = seat - 1;
break; if (!booked[idx]) throw new
InvalidSeatException("Seat " + seat + " is not
case 5: booked.");
running = false; if (!
System.out.println("Thank you for customerNames[idx].equals(customerName))
shopping!"); throw new InvalidSeatException("Only the
break; original booker can cancel this seat.");
booked[idx] = false;
default: customerNames[idx] = null;
System.out.println("Invalid choice. Try revenue -= ticketPrice;
again."); System.out.printf("Seat %d cancelled for %s.\n",
} seat, customerName);}
} public void displayBookings() {
System.out.printf("\nMovie: %s | Time: %s\
sc.close(); nTickets sold: %d/%d\nTotal revenue: $%.2f\n",
} movieName, timing, getBookedCount(),
} capacity, revenue);
7) Theatre-Booking-System boolean none = true;
import java.util.*; for (int i = 0; i < capacity; i++) {
class ShowFullException extends Exception { if (booked[i]) {
ShowFullException(String msg) { super(msg); }} System.out.printf("Seat %d booked by %s\
class InvalidSeatException extends Exception { n", i + 1, customerNames[i]);
InvalidSeatException(String msg) { super(msg); }} none = false;}}
class Show { if (none) System.out.println("No bookings
private final String movieName, timing; yet.");}
private final int capacity; public void displayAvailableSeats() {
private final double ticketPrice; System.out.printf("\nAvailable seats for %s at
private final boolean[] booked; %s:\n", movieName, timing);
private final String[] customerNames; boolean any = false;
private double revenue = 0; for (int i = 0; i < capacity; i++) {
public Show(String movieName, String timing, int if (!booked[i]) {
capacity, double ticketPrice) { System.out.print((i + 1) + " ");
this.movieName = movieName; any = true;}}
this.timing = timing; System.out.println(any ? "" : "No seats
this.capacity = capacity; available.");}
this.ticketPrice = ticketPrice; public int getBookedCount() {
booked = new boolean[capacity]; int count = 0;
customerNames = new String[capacity]; } for (boolean b : booked) if (b) count++;
public void bookSeats(List<Integer> seats, String return count;}
customerName) throws ShowFullException, public int getAvailableSeats() {
InvalidSeatException { return capacity - getBookedCount();}
if (getAvailableSeats() < seats.size()) public String getMovieName() { return
throw new ShowFullException("Not enough movieName; }
seats available!"); public String getTiming() { return timing; }
for (int seat : seats) validateSeat(seat); public int getCapacity() { return capacity; }
for (int seat : seats) { public double getTicketPrice() { return
int idx = seat - 1; ticketPrice; }
if (booked[idx]) throw new private void validateSeat(int seat) throws
InvalidSeatException("Seat " + seat + " already InvalidSeatException {
booked.");} if (seat < 1 || seat > capacity)
for (int seat : seats) {
throw new InvalidSeatException("Seat if (show == null) return;
number must be between 1 and " + capacity); }} System.out.print("Enter your name: ");
public class TheaterBookingSystem { String name = scanner.nextLine();
private static final Scanner scanner = new System.out.print("Enter seat number to cancel:
Scanner(System.in); ");
private static final List<Show> shows = new int seat = readInt();
ArrayList<>(List.of( try {
new Show("Avengers", "10:00 AM", 25, show.cancelSeat(seat, name);
12.50), } catch (InvalidSeatException e) {
new Show("Inception", "1:00 PM", 30, 10.00), System.out.println("Error: " +
new Show("Interstellar", "4:00 PM", 20, e.getMessage());}}
11.75), private static void viewAvailableSeats() {
new Show("The Matrix", "6:30 PM", 15, 9.00), Show show = selectShow();
new Show("Joker", "9:00 PM", 18, 8.50))); if (show != null) show.displayAvailableSeats();}
public static void main(String[] args) { private static void searchShows() {
while (true) { System.out.print("Enter movie name keyword to
System.out.println("\n--- Theater Booking search: ");
Menu ---"); String keyword =
System.out.println("1. Book Tickets"); scanner.nextLine().toLowerCase();
System.out.println("2. Cancel Ticket"); boolean found = false;
System.out.println("3. View All Bookings"); for (Show show : shows) {
System.out.println("4. View Available Seats"); if
System.out.println("5. Search Shows by Movie (show.getMovieName().toLowerCase().contains(key
Name"); word)) {
System.out.println("6. Exit"); System.out.printf("%s at %s (Seats: %d,
System.out.print("Choose option: "); Price: $%.2f)\n",
int choice = readInt(); show.getMovieName(),
switch (choice) { show.getTiming(), show.getCapacity(),
case 1 -> bookTickets(); show.getTicketPrice());
case 2 -> cancelTicket(); found = true;}}
case 3 -> if (!found) System.out.println("No shows found
shows.forEach(Show::displayBookings); matching that keyword.");}
case 4 -> viewAvailableSeats(); private static Show selectShow() {
case 5 -> searchShows(); System.out.println("Available Movies:");
case 6 -> { System.out.println("Exiting."); for (int i = 0; i < shows.size(); i++) {
return; } Show s = shows.get(i);
default -> System.out.println("Invalid System.out.printf("%d. %s at %s\n", i + 1,
option."); s.getMovieName(), s.getTiming());}
}}} System.out.print("Select show (1-" +
private static void bookTickets() { shows.size() + "): ");
Show show = selectShow(); int choice = readInt();
if (show == null) return; if (choice < 1 || choice > shows.size()) {
System.out.print("Enter your name: "); System.out.println("Invalid show selection.");
String name = scanner.nextLine(); return null; }
show.displayAvailableSeats(); return shows.get(choice - 1);}
System.out.print("Enter seat numbers to book private static int readInt() {
(comma separated): "); try {
String[] seatsInput = scanner.nextLine().split(","); return Integer.parseInt(scanner.nextLine());
List<Integer> seats = new ArrayList<>(); } catch (NumberFormatException e)
try { {return -1;} }}
for (String s : seatsInput)
seats.add(Integer.parseInt(s.trim())); Custom Exception
show.bookSeats(seats, name); class LimitExceededException extends Exception
} catch (NumberFormatException e) { { public LimitExceededException(String msg)
System.out.println("Invalid seat number { super(msg); } }
format.");
} catch (ShowFullException | Array List Usage
InvalidSeatException e) { ArrayList list = new ArrayList<>();
System.out.println("Error: " + list.add(new Bike("KA01AB1234"));
e.getMessage());}} for (Vehicle v : list)
private static void cancelTicket() { v.display(); }
Show show = selectShow();
8) Flight-Management-System System.out.print("\nEnter destination you
import java.util.*; want to book: ");
class Flight { String selectedDestination = sc.nextLine();
String destination;
String time; Flight selectedFlight = null;
double economyPrice; for (Flight f : available) {
public Flight(String destination, String time, if
double economyPrice) { (f.destination.equalsIgnoreCase(selectedDestination)
this.destination = destination; ){
this.time = time; selectedFlight = f;
this.economyPrice = economyPrice;} break;} }
public void display() { if (selectedFlight == null) {
System.out.println("Destination: " + destination System.out.println("Destination not found
+ ", Time: " + time + ", Economy Price: ₹" + or over your budget.");
economyPrice + ", Business Price: ₹" + return;}
(economyPrice * 1.5));}} System.out.print("Enter number of tickets: ");
public class FlightBookingSystem { int tickets = sc.nextInt();
static final double GST_RATE = 0.18; if (tickets <= 0) throw new
public static void main(String[] args) { IllegalArgumentException("Number of tickets must
Scanner sc = new Scanner(System.in); be positive.");
List<Flight> flights = new ArrayList<>(); double pricePerTicket =
flights.add(new Flight("Delhi", "08:00 AM", selectedFlight.economyPrice * classMultiplier;
4000)); double baseCost = pricePerTicket * tickets;
flights.add(new Flight("Mumbai", "09:30 AM", double gst = baseCost * GST_RATE;
4500)); double total = baseCost + gst;
flights.add(new Flight("Bangalore", "11:00 AM", System.out.println("\n🧾 BILL SUMMARY:");
5000)); System.out.println("Destination : " +
flights.add(new Flight("Chennai", "01:00 PM", selectedFlight.destination);
4200)); System.out.println("Time :"+
flights.add(new Flight("Kolkata", "04:00 PM", selectedFlight.time);
4700)); System.out.println("Class :"+
try { (flightClass.equals("business") ? "Business" :
System.out.println("Welcome to Flight "Economy"));
Booking System!"); System.out.println("Tickets : " + tickets);
System.out.print("Enter your budget: ₹"); System.out.println("Base Cost : ₹" +
double budget = sc.nextDouble(); baseCost);
sc.nextLine(); // consume newline System.out.println("GST (18%) : ₹" + gst);
System.out.print("Choose class System.out.println("Total Amount: ₹" + total);
(Economy/Business): "); System.out.println("\n Booking Confirmed.
String flightClass = Thank you for flying with us!");
sc.nextLine().trim().toLowerCase(); } catch (InputMismatchException e) {
if (!flightClass.equals("economy") && ! System.out.println(" Invalid input. Please
flightClass.equals("business")) { enter numbers where required.");
throw new } catch (IllegalArgumentException e) {
IllegalArgumentException("Invalid class selected. System.out.println("error " +
Choose 'Economy' or 'Business'."); } e.getMessage());
double classMultiplier = } catch (Exception e) {
flightClass.equals("business") ? 1.5 : 1.0; System.out.println(" An unexpected error
System.out.println("\nAvailable Flights under occurred: " + e.getMessage());
your budget:"); } finally {sc.close();}}}
List<Flight> available = new ArrayList<>();
for (Flight f : flights) {
double price = f.economyPrice *
classMultiplier;
if (price <= budget) {
f.display();
available.add(f);}}
if (available.isEmpty()) {
System.out.println("No flights available
under your budget for " + flightClass + " class.");
return; }