Advertisement
AntonStanoev

Exercise 5

Oct 28th, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | Source Code | 0 0
  1. public class Car {
  2.     private String brand;
  3.     private int speed;
  4.     private double fuel;
  5.     private double mileage;
  6.  
  7.     public Car(String brand, int speed, double fuel) {
  8.         this.brand = brand;
  9.         this.speed = speed;
  10.         this.fuel = fuel;
  11.         this.mileage = 0.0;
  12.     }
  13.  
  14.     public void accelerate() {
  15.         speed += 10;
  16.     }
  17.  
  18.     public void refuel(double amount) {
  19.         fuel += amount;
  20.     }
  21.  
  22.     public void drive(int distance) {
  23.         if (fuel > 0) {
  24.             double fuelConsumed = (double) distance / speed;
  25.             fuel -= fuelConsumed;
  26.             mileage += distance;
  27.             System.out.println("Distance: " + distance + " km.");
  28.             System.out.println("Mileage: " + mileage + " km.");
  29.             System.out.println("Left fuel: " + fuel + " l.");
  30.         } else {
  31.             System.out.println("Not enough fuel.");
  32.         }
  33.     }
  34.  
  35.     public static void main(String[] args) {
  36.         Car myCar = new Car("Audi", 60, 30.0);
  37.  
  38.         myCar.drive(200);
  39.         myCar.accelerate();
  40.         myCar.drive(150);
  41.         myCar.refuel(20.0);
  42.  
  43.         myCar.drive(100);
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement