0% found this document useful (0 votes)
8 views13 pages

Railway Ticket Reservation System in Java

The document presents a Railway Ticket Reservation System implemented in Java, utilizing classes for Ticket, Train, ReservationSystem, and Payment. It includes functionalities for booking and canceling tickets, viewing train and ticket details, and an admin interface for managing trains. The system simulates user and admin logins, payment processing, and ticket management with a simple console interface.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views13 pages

Railway Ticket Reservation System in Java

The document presents a Railway Ticket Reservation System implemented in Java, utilizing classes for Ticket, Train, ReservationSystem, and Payment. It includes functionalities for booking and canceling tickets, viewing train and ticket details, and an admin interface for managing trains. The system simulates user and admin logins, payment processing, and ticket management with a simple console interface.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dhanush.A.

R
202217B2120

Railway ticket reservation system using UML and Java


import [Link].*;

class Ticket {

private int ticketNumber;

private String passengerName;

private int seatNumber;

private String ticketClass;

public Ticket(int ticketNumber, String passengerName, int seatNumber, String ticketClass) {

[Link] = ticketNumber;

[Link] = passengerName;

[Link] = seatNumber;

[Link] = ticketClass;

public void displayTicketDetails() {

[Link]("Ticket Details:");

[Link]("Ticket Number: " + ticketNumber);

[Link]("Passenger Name: " + passengerName);

[Link]("Seat Number: " + seatNumber);

[Link]("Class: " + ticketClass);

public int getTicketNumber() {

return ticketNumber;

public String getPassengerName() {

return passengerName;
Dhanush.A.R
202217B2120

class Train {

private int trainNumber;

private String trainName;

private String departureTime;

private String route;

public Train(int trainNumber, String trainName, String departureTime, String route) {

[Link] = trainNumber;

[Link] = trainName;

[Link] = departureTime;

[Link] = route;

public void displayTrainDetails() {

[Link]("Train Details:");

[Link]("Train Number: " + trainNumber);

[Link]("Train Name: " + trainName);

[Link]("Departure Time: " + departureTime);

[Link]("Route: " + route);

public int getTrainNumber() {

return trainNumber;

class ReservationSystem {

private static int totalTicketsBooked = 0;


Dhanush.A.R
202217B2120

private static List<Ticket> bookedTickets = new ArrayList<>();

private static List<Train> availableTrains = new ArrayList<>();

private static final List<String> validTicketClasses = [Link]("1A", "2A", "3A", "SL");

static {

// Initialize some dummy trains

[Link](new Train(12007, "Shatabdi Express", "06: 00", "Chennai to Mysore"));

[Link](new Train(12759, "Charminar Express", "18: 10", "Chennai to


Hyderabad"));

public static boolean bookTicket(String passengerName, int numberOfSeats, String


ticketClass) {

if (![Link](ticketClass)) {

[Link]("Invalid ticket class.");

return false;

if (numberOfSeats > 0) {

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

int ticketNumber = totalTicketsBooked + 1;

int seatNumber = totalTicketsBooked + 1; // Assuming seat number assignment

Ticket ticket = new Ticket(ticketNumber, passengerName, seatNumber, ticketClass);

[Link](ticket);

totalTicketsBooked++;

return true;

} else {

return false;

}
Dhanush.A.R
202217B2120

public static boolean cancelTicket(int ticketNumber) {

Iterator<Ticket> iterator = [Link]();

while ([Link]()) {

Ticket ticket = [Link]();

if ([Link]() == ticketNumber) {

[Link]();

[Link]("Ticket cancelled successfully.");

return true;

[Link]("Ticket not found.");

return false;

public static void viewTicketDetails() {

for (Ticket ticket : bookedTickets) {

[Link]();

[Link]("-------------------------");

public static void viewTrainDetails() {

for (Train train : availableTrains) {

[Link]();

[Link]("-------------------------");

public static void addTrain(int trainNumber, String trainName, String departureTime, String
route) {
Dhanush.A.R
202217B2120

[Link](new Train(trainNumber, trainName, departureTime, route));

[Link]("Train added successfully.");

public static void removeTrain(int trainNumber) {

Iterator<Train> iterator = [Link]();

while ([Link]()) {

Train train = [Link]();

if ([Link]() == trainNumber) {

[Link]();

[Link]("Train removed successfully.");

return;

[Link]("Train not found.");

public static int getTotalTicketsBooked() {

return totalTicketsBooked;

public static List<Train> getAvailableTrains() {

return availableTrains;

class Payment {

public static boolean processPayment(double amount) {

// Simulate payment processing

Scanner scanner = new Scanner([Link]);

[Link]("Payment processing...");
Dhanush.A.R
202217B2120

[Link]("Enter payment amount: " + amount);

double enteredAmount = [Link]();

[Link](); // Consume newline

if (enteredAmount >= amount) {

[Link]("Payment successful.");

return true;

} else {

[Link]("Payment failed. Insufficient amount.");

return false;

public class RailwayTicketReservationSystem {

private static Scanner scanner = new Scanner([Link]);

private static boolean loggedIn = false;

public static void main(String[] args) {

int choice;

do {

[Link]("1. User Login");

[Link]("2. View Ticket Details");

[Link]("3. View Train Details");

[Link]("4. Admin Login");

[Link]("5. Exit");

[Link]("Enter your choice: ");

choice = [Link]();

[Link](); // Consume newline

switch (choice) {
Dhanush.A.R
202217B2120

case 1:

if (login()) {

userMenu();

} else {

[Link]("Login failed. Please try again.");

break;

case 2:

[Link]();

break;

case 3:

[Link]();

break;

case 4:

if (adminLogin()) {

adminMenu();

} else {

[Link]("Admin login failed. Please try again.");

break;

case 5:

[Link]("Exiting...");

break;

default:

[Link]("Invalid choice. Please enter again.");

} while (choice != 5);

[Link]();

}
Dhanush.A.R
202217B2120

private static boolean login() {

// Simulated user login

[Link]("Enter username: ");

String username = [Link]();

[Link]("Enter password: ");

String password = [Link]();

// Simulate authentication

if ("user".equals(username) && "password".equals(password)) {

loggedIn = true;

[Link]("Login successful.");

return true;

} else {

return false;

private static void userMenu() {

int choice;

do {

[Link]("User Menu:");

[Link]("1. Book Ticket");

[Link]("2. Cancel Ticket");

[Link]("3. View Ticket Details");

[Link]("4. View Train Details");

[Link]("5. Logout");

[Link]("Enter your choice: ");

choice = [Link]();

[Link](); // Consume newline

switch (choice) {

case 1:
Dhanush.A.R
202217B2120

bookTicket();

break;

case 2:

cancelTicket();

break;

case 3:

[Link]();

break;

case 4:

[Link]();

break;

case 5:

loggedIn = false;

[Link]("Logged out.");

break;

default:

[Link]("Invalid choice. Please enter again.");

} while (choice != 5);

private static void bookTicket() {

[Link]("Enter passenger name: ");

String passengerName = [Link]();

[Link]("Enter number of seats: ");

int numberOfSeats = [Link]();

[Link](); // Consume newline

[Link]("Enter ticket class (1A, 2A, 3A, SL): ");

String ticketClass = [Link]();


Dhanush.A.R
202217B2120

boolean booked = [Link](passengerName, numberOfSeats,


ticketClass);

if (booked) {

double amount = calculateAmount(ticketClass, numberOfSeats);

if ([Link](amount)) {

[Link]("Your ticket(s) have been booked.");

[Link]("Total tickets booked so far: " +


[Link]());

} else {

[Link]("Payment failed. Ticket booking cancelled.");

} else {

[Link]("Tickets not available in " + ticketClass);

private static void cancelTicket() {

[Link]("Enter ticket number to cancel: ");

int ticketNumber = [Link]();

[Link](); // Consume newline

boolean cancelled = [Link](ticketNumber);

if (cancelled) {

[Link]("Ticket cancellation successful.");

} else {

[Link]("Ticket cancellation failed.");

private static double calculateAmount(String ticketClass, int numberOfSeats) {

double rate;
Dhanush.A.R
202217B2120

switch (ticketClass) {

case "1A":

rate = 2000.0;

break;

case "2A":

rate = 1500.0;

break;

case "3A":

rate = 1000.0;

break;

case "SL":

rate = 500.0;

break;

default:

throw new IllegalArgumentException("Invalid ticket class");

return rate * numberOfSeats;

private static boolean adminLogin() {

// Simulated admin login

[Link]("Enter admin username: ");

String username = [Link]();

[Link]("Enter admin password: ");

String password = [Link]();

// Simulate authentication

if ("admin".equals(username) && "adminpassword".equals(password)) {

loggedIn = true;

[Link]("Admin login successful.");

return true;

} else {
Dhanush.A.R
202217B2120

return false;

private static void adminMenu() {

int choice;

do {

[Link]("Admin Menu:");

[Link]("1. Add Train");

[Link]("2. Remove Train");

[Link]("3. Logout");

[Link]("Enter your choice: ");

choice = [Link]();

[Link](); // Consume newline

switch (choice) {

case 1:

addTrain();

break;

case 2:

removeTrain();

break;

case 3:

loggedIn = false;

[Link]("Logged out.");

break;

default:

[Link]("Invalid choice. Please enter again.");

} while (choice != 3);

}
Dhanush.A.R
202217B2120

private static void addTrain() {

[Link]("Enter train number: ");

int trainNumber = [Link]();

[Link](); // Consume newline

[Link]("Enter train name: ");

String trainName = [Link]();

[Link]("Enter departure time: ");

String departureTime = [Link]();

[Link]("Enter route: ");

String route = [Link]();

[Link](trainNumber, trainName, departureTime, route);

private static void removeTrain() {

[Link]("Enter train number to remove: ");

int trainNumber = [Link]();

[Link](); // Consume newline

[Link](trainNumber);

Common questions

Powered by AI

The system assumes initial train schedules are predefined, with dummy trains loaded during initialization . Administrators can add new trains by specifying details like train number, name, departure time, and route, and these are stored in the availableTrains list . Trains can be removed by matching train numbers against existing entries. This method relies on accurate, unique identification (train numbers) for data manipulation, assuming that each train number refers to a distinct and valid entity in the system.

User authentication is integral to determining access to functionalities in the system. For users, authentication involves checking credentials ('user' as username and 'password' as password) to allow access to the user menu, where tickets can be booked or cancelled . Admin authentication uses different criteria ('admin' as username and 'adminpassword' as password) and grants access to admin-specific tasks, such as adding or removing trains . This separation ensures that sensitive operations, like modifying train details, are protected from unauthorized access.

The system performs input validation at several points: it checks user-entered values for ticket classes against a valid list and ensures payment amounts are sufficient during transactions . These validation steps are crucial for maintaining system integrity by preventing inappropriate or unauthorized operations, such as booking with invalid classes or proceeding with insufficient funds. They safeguard the system's data against corruption, provide reliable user feedback, and reduce the risk of runtime errors from invalid input.

The system distinguishes functionalities through separate login processes for users and administrators, each verifying credentials before granting access to menus specific to their roles . Users access options primarily concerned with viewing, booking, and cancelling tickets. In contrast, administrators are provided with functionalities to manage train details, such as adding or removing trains. This division enforces access control, ensuring operational integrity by restricting sensitive actions to authenticated administrators only.

Ticket class validation is handled by verifying the ticket class input against a predefined list of valid classes ("1A", "2A", "3A", "SL") during the booking process . If an invalid class is entered, the booking is denied, and a corresponding message is displayed to the user. This approach ensures that users cannot book tickets with non-existent classes, maintaining data integrity and preventing errors related to incorrect ticket classification. It encourages users to adhere to accepted standards and provides immediate feedback on valid options.

Using static methods and variables in the ReservationSystem promotes simplicity and enables easy access to reservation functionality without needing object instantiation, which can enhance performance and reduce memory usage . However, this design choice comes with drawbacks: it limits flexibility, such as handling multiple instances or states simultaneously; and it may hinder testability, as static contexts are less adaptable to unit tests requiring different runtime states. This approach simplifies implementation but at the cost of reduced abstraction and scalability.

Seat allocation within the system is directly tied to ticket booking. For each ticket booked, a seat number is assigned automatically, assumed to be sequential starting from the next available number (totalTicketsBooked + 1). This method assumes a simple model where seats are infinite and assigned purely based on sequence rather than availability per train, reflecting a system that does not incorporate dynamic seat management or real-time availability checks.

The ReservationSystem manages the number of booked tickets using a static variable, totalTicketsBooked, which acts as a counter and is incremented every time a ticket is successfully booked . This ensures that the system maintains an accurate count of booked tickets. The bookedTickets list tracks individual ticket details, fostering data consistency by recording each ticket creation and its association with the passenger .

The system's payment process simulates real-world scenarios by prompting the user to confirm the payment amount, allowing users to input the payment amount and validating whether it meets or exceeds the required amount . By checking for sufficient payment, the system prevents underpayment and ensures successful transaction handling. This user input validation is crucial for simulating realistic payment transactions, though in a real-world application, an interface with a financial service would be necessary.

Train and ticket details are displayed using simple console outputs that iterate over lists of booked tickets and available trains, printing their properties to the console . While this approach is straightforward, improvements like implementing a graphical user interface (GUI) would enhance usability by offering a more intuitive, visually appealing, and interactive experience. Additionally, integrating filtering and sorting functionalities would help users better manage and analyze the displayed data, making it easier to navigate through options and details.

You might also like