Advertisement
Guest User

Car

a guest
Jun 3rd, 2020
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.21 KB | None | 0 0
  1. <?php
  2.  
  3. class Car
  4. {
  5.     private $speed;
  6.     private $fuel;
  7.     private $consumption;
  8.     private $totalDistance;
  9.  
  10.     public function __construct(float $speed, float $fuel, float $consumption)
  11.     {
  12.         $this->speed = $speed;
  13.         $this->fuel = $fuel;
  14.         $this->consumption = $consumption;
  15.         $this->totalDistance = 0;
  16.     }
  17.  
  18.     public function getDistance(): float
  19.     {
  20.         return $this->totalDistance;
  21.     }
  22.  
  23.     public function getFuel(): float
  24.     {
  25.         return $this->fuel;
  26.     }
  27.  
  28.     public function getTime(): string
  29.     {
  30.         $time = $this->totalDistance / $this->speed;
  31.         $hours = floor($time);
  32.         $minutes = floor(($time - $hours) * 60);
  33.         return "$hours hours and $minutes minutes";
  34.     }
  35.  
  36.     public function refuel(float $liters) //: void
  37.     {
  38.         $this->fuel += $liters;
  39.     }
  40.  
  41.     public function travel(float $distance) //: void
  42.     {
  43.         $canTravelDistance = $this->fuel * 100 / $this->consumption;
  44.         if ($distance >= $canTravelDistance) {
  45.             $this->totalDistance += $canTravelDistance;
  46.             $this->fuel = 0;
  47.         } else {
  48.             $this->totalDistance += $distance;
  49.             $fuelSpend = $distance * $this->consumption / 100;
  50.             $this->fuel -= $fuelSpend;
  51.         }
  52.     }
  53. }
  54.  
  55. list($speed, $fuel, $consumption) = array_map('floatval', explode(" ", readline()));
  56. $car = new Car($speed, $fuel, $consumption);
  57. $line = readline();
  58. while ($line != "END") {
  59.     $command = explode(" ", $line);
  60.     switch ($command[0]) {
  61.         case "Travel":
  62.             $distance = floatval($command[1]);
  63.             $car->travel($distance);
  64.             break;
  65.         case "Refuel":
  66.             $liters = floatval($command[1]);
  67.             $car->refuel($liters);
  68.             break;
  69.         case "Distance":
  70.             echo "Total Distance: " . number_format($car->getDistance(), 1, '.', "") . PHP_EOL;
  71.             break;
  72.         case "Time":
  73.             echo "Total Time: " . $car->getTime() . PHP_EOL;
  74.             break;
  75.         case "Fuel":
  76.             echo "Fuel left: " . number_format($car->getFuel(), 1, '.', "") . " liters" . PHP_EOL;
  77.             break;
  78.     }
  79.     $line = readline();
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement