C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Class & Object Based Program - Railway Ticket - Java Programs


Design a class RailwayTicket with following description:


Instance variables/data members:
String name: to store the name of the customer
String coach: to store the type of coach the customer wants to travel
long mobNo: To store the customer’s mobile number
int amt: to store basic amount of ticket
int totalAmt: To store the amount to be paid after updating the original amount


Member methods:
void accept() – to take input for name, coach, mobile number and amount
void update() – to update the amount as per the coach selected
(extra amount to be added in the amount as follows)

Type of Coaches

Amount

First_AC

700

Second_AC

500

Third_AC

250

sleeper

None

void display() – to display all details of a customer such as name, coach, total amount and mobile number


Write a main() method to create an object of the class and call the above member methods.

import java.util.Scanner; class RailwayTicket{ String name; String coach; long mobNo; int amt; int totalAmt; public void accept(){ Scanner in = new Scanner(System.in); System.out.print("Name: "); name = in.nextLine(); System.out.print("Coach: "); coach = in.nextLine(); System.out.print("Mobile number: "); mobNo = Long.parseLong(in.nextLine()); System.out.print("Amount: "); amt = Integer.parseInt(in.nextLine()); } public void update(){ if(coach.equalsIgnoreCase("First_AC")) totalAmt = amt + 700; else if(coach.equalsIgnoreCase("Second_AC")) totalAmt = amt + 500; else if(coach.equalsIgnoreCase("Third_AC")) totalAmt = amt + 250; else totalAmt = amt; } public void display(){ System.out.println("Name: " + name); System.out.println("Coach: " + coach); System.out.println("Total amount: " + totalAmt); System.out.println("Mobile Number: " + mobNo); } public static void main(String[] args) { RailwayTicket obj = new RailwayTicket(); obj.accept(); obj.update(); obj.display(); } }

Output

 
 OUTPUT 1: 
Name: Anand Rao
Coach: First_AC
Mobile number: 1234567890
Amount: 5100

Name: Anand Rao
Coach: First_AC
Total amount: 5800
Mobile Number: 1234567890 

 OUTPUT 2: 
Name: Ajay Singh
Coach: Second_AC
Mobile number: 1234567890
Amount: 3750

Name: Ajay Singh
Coach: Second_AC
Total amount: 4250
Mobile Number: 1234567890
 
 OUTPUT 3: 
Name: Jayanta Roy
Coach: Sleeper
Mobile number: 1234567890
Amount: 680

Name: Jayanta Roy
Coach: Sleeper
Total amount: 680
Mobile Number: 1234567890