THINK FIRST·CODE LATER

← All labs

Highway tolls: overriding methods

Problem

Write a superclass Vehicle (protected plate and km, toll() = 0.5 yuan per km, type(), and toString() formatted %-6s %-9s %4d km toll %7.2f using type() and toll()), and three subclasses that override toll() and type():

  • Car(plate, km, electric) — electric cars pay 20 % less than the base toll (super.toll()), type Car or Car-EV;
  • Truck(plate, km, axles) — base toll × axles / 2 + 10, type Truck3 etc.;
  • Bus(plate, km) — 1.5 × base toll, capped at 120.

TollStation.main reads car PLATE KM true|false, truck PLATE KM AXLES or bus PLATE KM lines into a Vehicle[], prints each vehicle and Total collected: … yuan from n vehicles.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l14-2-data-1.txt

car AB123 100 false
car EV777 100 true
truck TR01 100 3
bus BUS9 100
What your program must print for l14-2-data-1.txt
Car    AB123      100 km  toll   50.00
Car-EV EV777      100 km  toll   40.00
Truck3 TR01       100 km  toll   85.00
Bus    BUS9       100 km  toll   75.00
Total collected: 250.00 yuan from 4 vehicles

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l14-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content l14-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.