1. Design and code a program including the following classes, as well as a clien
ID: 3533078 • Letter: 1
Question
1. Design and code a program including the following classes, as well as a client class to test all the methods coded:<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
A Passenger class, encapsulating a passenger. A passenger has two attributes: a name, and a class of service, which will be 1 or 2.
A Train class, encapsulating a train of passengers. A train of passengers has one attribute: a list of passengers, which must be represented with an ArrayList. Your constructor will build the list of passengers by reading date from a file called passengers.txt (that you would create). You can assume that passengers.txt has the following format:
<name1> <class1>
<name2> <class2>
Explanation / Answer
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
class Passenger
{
String name;
int classofservice;
public Passenger()
{
name="";
classofservice=0;
}
}
class Train extends Passenger
{
ArrayList<Passenger> Train= new ArrayList<Passenger>();
public Train()
{
try
{
Scanner s=new Scanner(new BufferedReader(new FileReader("A.txt")));
Passenger P =new Passenger();
while(s.hasNext())
{
P.name=s.next();
P.classofservice=s.nextInt();
Train.add(P);
}
}
catch(IOException e)
{
System.out.println("File not found!!!");
}
}
public float percentInFirst()
{
int n=Train.size();
int no=0;
Passenger P=new Passenger();
for(int i=0;i<n;i++)
{
P=Train.get(i);
if(P.classofservice==1)
{
no++;
}
}
return (float)(no*100/n);
}
public int revenue(int a,int b)
{
int n=Train.size();
int rev=0;
Passenger P=new Passenger();
for(int i=0;i<n;i++)
{
P=Train.get(i);
if(P.classofservice==1)
{
rev=rev+a;
}
else
{
rev=rev+b;
}
}
return rev;
}
public boolean isExist(String name)
{
int n=Train.size();
Passenger P=new Passenger();
for(int i=0;i<n;i++)
{
P=Train.get(i);
if(P.name==name)
{
return true;
}
}
return false;
}
}
class Mukesh
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
Train T =new Train();
System.out.println("Enter the price for first class and second class");
int a=s.nextInt();
int b=s.nextInt();
System.out.println("Revenue is "+T.revenue(a,b));
System.out.println("Enter the name of person to search");
String name=s.next();
if(T.isExist(name))
{
System.out.println("Person "+name+" is on the train");
}
else
{
System.out.println("Person "+name+" is not on the train");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.