Question

Your solutions to this assignment MUST be implemented in functional style (using lambdas and streams), whenever...

Your solutions to this assignment MUST be implemented in functional style (using lambdas and streams), whenever possible.

Needs help with part 3 only:

   1.   Complete the Train constructor (verify that the data is correct)
   a.   carrier must be one of the following: "Canadian National Railway", "Canadian Pacific Railway", "Hudson Bay Railway Co", "Quebec North Shore and Labrador Railway", "RailLink Canada", "Tshiuetin Rail Transportation", "Via Rail";
   b.   trainNumber must be between 1 and 999;
   c.   platform must be between 1 and 26;
   d.   departureTime and arrivalTime must be in a 24 hours format, with leading zeros and ":" separating the hours and minutes (e.g. 00:25, 05:45, 12:01, 17:34, 23:58);
   e.   destination must be one of the following: "Toronto", "Labrador City", "Montreal", "Edmonton", "Vancouver", "Winnipeg", "Halifax", "Ottawa";
   f.   verification code must be written in the methods checkCarrier, checkTrainNumber, checkPlatform, checkTime and checkDestination. These methods will be called from within the constructor.


   2.   In the class Train, implement the methods printInfo and tripDuration

   3.   In the class TrainStation, implement the constructor and the following methods (headers are provided)
   a.   addTrain
   b.   printAllTrains
   c.   printTrainsTo
   d.   printTrainsBefore
   e.   printTrainsToBefore
   f.   printTrainsAfter
   g.   platformDepartures
   h.   numberOfTrainsTo

   4.   In the class TrainStation implement the methods (headers are provided)
   a.   cancelTrain
   b.   cancelTrainsTo

   5.   In the class TrainStation, implement the method createTrains, which creates at least 5 train trips and replaces the existing timetable. This will allow you to test your code.

trainStation Code:

import java.util.ArrayList;
/**
* Write a description of class TrainStation here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TrainStation
{
// timetable
private ArrayList<Train> xx;

/**
* Constructor for objects of class UniversityRegistrar
*/
public TrainStation()
{
// initialise instance variables
  
}
  
/**
* Add the trains recorded in the given filename to the timetable (replacing previous flights).
* @param filename A CSV file of Train records.
*/
public void addTrainsFromFile(String filename)
{
TrainReader reader = new TrainReader();
xx = new ArrayList<>();
xx.addAll(reader.getTrains(filename));
}

/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public void addTrain(String depTime,String arrTime, String destination, String carrierName, int trainNumber, int platform )
{
// adds a single train to the timetable
}
  
public void printAllTrains()
{
// prints for all trains the corresponding info
// trains are separated by an empty line
}
  
public void printList()
{
for(Train record : xx) {
System.out.println(record.getDetails());
}
}
  
public void printTrainsTo(String destination)
{
// prints all trains to the given destination
// trains are separated by an empty line
}
  
public void printTrainsBefore(String time)
{
// prints all trains which depart before the given time
// one train per line
}
  
public void printTrainsToBefore(String destination,String time)
{
// prints all trains to the given destination which depart before the given time
// one train per line
}
  
public void printTrainsAfter(String tt)
{
// prints all trains which depart after the given time
// one train per line
}
  
public void platformDepartures(int a)
{
// prints all trains that depart from the given platform
// one train per line
}
  
public int numberOfTrainsTo(String z)
{
// returns number of trains to a given destination
return 0;
}
  
public void cancelTrain(int trainNumber, String carrierName)
{
// removes given train from the timetable
}
  
public void cancelTrainsTo(String y)
{
// removes all trains to the given destination from the the timetable
}
  
}

Homework Answers

Answer #1

Short Summary:

  • Implemented part 3 method as per the requirement
  • Attached source code and screenshots
  • Note: As the Train class is not given, have created one with given order of instance variables. Please change the order, if required

**************Please do upvote to appreciate our time. Thank you!******************

Source Code:

TrainStation.java

import java.io.File;
import java.io.FileNotFoundException;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
* Write a description of class TrainStation here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class TrainStation
{
// timetable
private ArrayList<Train> timeTable;

/**
* Constructor for objects of class UniversityRegistrar
*/
public TrainStation()
{
// initialise instance variables
   timeTable=new ArrayList<>();
  
}
  
/**
* Add the trains recorded in the given filename to the timetable (replacing previous flights).
* @param filename A CSV file of Train records.
* @throws FileNotFoundException
*/
public void addTrainsFromFile(String filename) throws FileNotFoundException
{
   Scanner file=new Scanner(new File("C:\\Users\\asus\\"+filename));
   while(file.hasNext())
   {
       String[] trainArray=file.nextLine().split(",");
       timeTable.add(new Train(trainArray[0],trainArray[1],trainArray[2],trainArray[3],Integer.parseInt(trainArray[4]),Integer.parseInt(trainArray[4])));
   }
   file.close();

}

/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public void addTrain(String depTime,String arrTime, String destination, String carrierName, int trainNumber, int platform )
{
// adds a single train to the timetable
   timeTable.add(new Train(depTime,arrTime,destination,carrierName,trainNumber,platform));

}
  
public void printAllTrains()
{
// prints for all trains the corresponding info
// trains are separated by an empty line
   timeTable.forEach(s -> System.out.println(s.toString()+"\n"));
}
  
public void printList()
{
   timeTable.forEach(s -> System.out.println(s.toString()));


}

  
public void printTrainsTo(String destination)
{
// prints all trains to the given destination
// trains are separated by an empty line
   List<Train> trainList = timeTable.stream()
           .filter(n -> n.getDestination().equalsIgnoreCase(destination))
           .collect(Collectors.toList());
   trainList.forEach(s -> System.out.println(s.toString()+"\n"));
  
}
  
public void printTrainsBefore(String time)
{
// prints all trains which depart before the given time
// one train per line
   String [] timeArr=time.split(":");
   LocalTime givenTime=LocalTime.of(Integer.parseInt(timeArr[0]),Integer.parseInt( timeArr[1]));
  
   for(Train train:timeTable)
   {
       String [] depTimeArr=train.getDepTime().split(":");
       LocalTime departTime=LocalTime.of(Integer.parseInt(depTimeArr[0]),Integer.parseInt( depTimeArr[1]));

       if(departTime.isBefore(givenTime))
           System.out.println(train.toString());
   }
}
  
public void printTrainsToBefore(String destination,String time)
{
// prints all trains to the given destination which depart before the given time
// one train per line
   String [] timeArr=time.split(":");
   LocalTime givenTime=LocalTime.of(Integer.parseInt(timeArr[0]),Integer.parseInt( timeArr[1]));
  
   for(Train train:timeTable)
   {
       String [] depTimeArr=train.getDepTime().split(":");
       LocalTime departTime=LocalTime.of(Integer.parseInt(depTimeArr[0]),Integer.parseInt( depTimeArr[1]));

       if(departTime.isBefore(givenTime) && train.getDestination().equalsIgnoreCase(destination))
           System.out.println(train.toString());
   }
}
  
public void printTrainsAfter(String tt)
{
// prints all trains which depart after the given time
// one train per line
   String [] timeArr=tt.split(":");
   LocalTime givenTime=LocalTime.of(Integer.parseInt(timeArr[0]),Integer.parseInt( timeArr[1]));
  
   for(Train train:timeTable)
   {
       String [] depTimeArr=train.getDepTime().split(":");
       LocalTime departTime=LocalTime.of(Integer.parseInt(depTimeArr[0]),Integer.parseInt( depTimeArr[1]));

       if(departTime.isAfter(givenTime))
           System.out.println(train.toString());
   }
}
  
public void platformDepartures(int a)
{
// prints all trains that depart from the given platform
// one train per line
   List<Train> trainList = timeTable.stream()
           .filter(n -> n.getPlatform()==a)
           .collect(Collectors.toList());
   trainList.forEach(s -> System.out.println(s.toString()+"\n"));
  
}
  
public int numberOfTrainsTo(String z)
{
// returns number of trains to a given destination
   List<Train> trainList = timeTable.stream()
           .filter(n -> n.getDestination().equalsIgnoreCase(z))
           .collect(Collectors.toList());
   trainList.forEach(s -> System.out.println(s.toString()+"\n"));
return trainList.size();
}
  
public void cancelTrain(int trainNumber, String carrierName)
{
// removes given train from the timetable
   Iterator <Train> iter=timeTable.iterator();
   while(iter.hasNext())
   {
       Train trainObj=iter.next();
       if(trainObj.getTrainNumber()==trainNumber && trainObj.getCarrierName().equalsIgnoreCase(carrierName))
           iter.remove();
   }
}
  
public void cancelTrainsTo(String y)
{
// removes all trains to the given destination from the the timetable
   Iterator <Train> iter=timeTable.iterator();
   while(iter.hasNext())
   {
       Train trainObj=iter.next();
       if(trainObj.getDestination().equalsIgnoreCase(y))
           iter.remove();
   }
}
  
}

Train.java

This class is not provided in the question. Have added this to code Trainstation class. Please rearrange the instance variables(in constructor/method calls of Trainstation.java) if it's not in required order

//This class stores the train information
public class Train {
   String depTime;
   String arrTime; String destination; String carrierName; int trainNumber; int platform;
   public Train(String depTime, String arrTime, String destination, String carrierName, int trainNumber,
           int platform) {
       this.depTime = depTime;
       this.arrTime = arrTime;
       this.destination = destination;
       this.carrierName = carrierName;
       this.trainNumber = trainNumber;
       this.platform = platform;
   }
   public String getDepTime() {
       return depTime;
   }
   public String getArrTime() {
       return arrTime;
   }
   public String getDestination() {
       return destination;
   }
   public String getCarrierName() {
       return carrierName;
   }
   public int getTrainNumber() {
       return trainNumber;
   }
   public int getPlatform() {
       return platform;
   }
}

**************Please do upvote to appreciate our time. Thank you!******************

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
in jGRASP INVENTORY CLASS You need to create an Inventory class containing the private data fields,...
in jGRASP INVENTORY CLASS You need to create an Inventory class containing the private data fields, as well as the methods for the Inventory class (object). Be sure your Inventory class defines the private data fields, at least one constructor, accessor and mutator methods, method overloading (to handle the data coming into the Inventory class as either a String and/or int/float), as well as all of the methods (methods to calculate) to manipulate the Inventory class (object). The data fields...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with the default values denoted by dataType name : defaultValue - String animal : empty string - int lapsRan : 0 - boolean resting : false - boolean eating : false - double energy : 100.00 For the animal property implement both getter/setter methods. For all other properties implement ONLY a getter method Now implement the following constructors: 1. Constructor 1 – accepts a String...
Objectives:The focus of this assignment is to create and use a recursive method given a moderately...
Objectives:The focus of this assignment is to create and use a recursive method given a moderately difficult problem. Program Description: This project will alter the EmployeeManager to add a search feature, allowing the user to find an Employee by a substring of their name. This will be done by implementing the Rabin-Karp algorithm. A total of seven classes are required. Employee (From previous assignment) HourlyEmployee (From previous assignment) SalaryEmployee (From previous assignment) CommissionEmployee (From previous assignment) EmployeeManager (Altered from previous...
MUST WRITE IN C++ Objective: Learn how to design classes using abstract classes and inheritance Assignment:...
MUST WRITE IN C++ Objective: Learn how to design classes using abstract classes and inheritance Assignment: MUST WRITE IN C++ Objective: Learn how to design classes using abstract classes and inheritance Assignment: In cryptography, encryption is the process of encoding a message or information in such a way that only authorized parties can access it. In this lab you will write a program to decode a message that has been encrypted using two different encryption algorithms. Detailed specifications: Define an...
Code in JAVA The requirements are as follows: The input will be in a text file...
Code in JAVA The requirements are as follows: The input will be in a text file whose name is given by arg[0] of main(). It will contain a fully-parenthesized infix expression containing only: "(", ")", "+", "-" and integers. Need help on the main and fixing the Queue. //Input: ( ( 1 + 2 ) - ( ( 3 - 4 ) + ( 7 - 2 ) ) ) ( ( 1 + 2 ) - ( 3 -...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 565 Error 2 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 761 I need this code to COMPILE and RUN, but I cannot get rid of this error. Please Help!! #include #include #include #include using namespace std; enum contactGroupType {// used in extPersonType FAMILY, FRIEND, BUSINESS, UNFILLED }; class addressType { private:...
You will be traversing through an integer tree to print the data. Given main(), write the...
You will be traversing through an integer tree to print the data. Given main(), write the methods in the 'IntegerBinaryTree' class specified by the // TODO: sections. There are 6 methods in all to write. Ex: If the input is 70 86 60 90 49 62 81 85 38 -1 the output should be: Enter whole numbers to insert into the tree, -1 to stop Inorder: 38 - 49 - 60 - 62 - 70 - 81 - 85 -...
Using Java, please implement the Poker and PokerHand classes to provide the expected output using the...
Using Java, please implement the Poker and PokerHand classes to provide the expected output using the CardDemo class. Rules are the following: - Deck and PockerHand should be Iterable (note that you may just reuse one of the underlying iterators to provide this functionality) - Poker should implement 2 methods checking for two possible poker hands , see the comments inside the classes for details. Hint: remember how one can count the frequency of words in text? - whenever you...
Compile and execute the application. You will discover that is has a bug in it -...
Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn. Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code. Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(),...
The language is Java. Using a singly-linked list, implement the four queue methods enqueue(), dequeue(), peek(), and isEmpty(). For this assignment, enqueue() will be implemented in an unusual manner. That is, in the version of enqueue() we will use, if the element being processed is already in the queue then the element will not be enqueued and the equivalent element already in the queue will be placed at the end of the queue. Additionally, you must implement a circular queue....
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT