Advertisement
STANAANDREY

gas station

Oct 16th, 2023
1,034
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. class Car {
  2.     private String matNr;
  3.     private int necFuel;
  4.     public Car(final String matNr, int necFuel) {
  5.         this.matNr = matNr;
  6.         this.necFuel = necFuel;
  7.     }
  8.  
  9.     public int getNecFuel() {
  10.         return necFuel;
  11.     }
  12.  
  13.     @Override
  14.     public String toString() {
  15.         return matNr + " - " + necFuel + "\n";
  16.     }
  17. }
  18.  
  19. class GasStation {
  20.     private int fuel = 0;
  21.     private Car[] cars;
  22.     private int len = 0;
  23.  
  24.     public GasStation() {
  25.         cars = new Car[10];
  26.     }
  27.  
  28.     boolean feedCar(final Car car) {
  29.         if (fuel >= car.getNecFuel()) {
  30.             fuel -= car.getNecFuel();
  31.             return true;
  32.         }
  33.         if (len != cars.length) {
  34.             cars[len++] = car;
  35.             return true;
  36.         }
  37.         return false;
  38.     }
  39.  
  40.     @Override
  41.     public String toString() {
  42.         String string = "GS: " + fuel + " Q:\n";
  43.         for (int i = 0; i < len; i++) {
  44.             string += cars[i];
  45.         }
  46.         return string;
  47.     }
  48.  
  49.     public void feedMe(int fuel) {
  50.         this.fuel += fuel;
  51.         int cnt = 0;
  52.         while (cars[cnt] != null && this.fuel >= cars[cnt].getNecFuel()) {
  53.             this.fuel -= cars[cnt].getNecFuel();
  54.             cnt++;
  55.         }
  56.         for (int i = cnt; i < len; i++) {
  57.             cars[i - cnt] = cars[i];
  58.             cars[i] = null;
  59.         }
  60.         len -= cnt;
  61.     }
  62. }
  63.  
  64. public class Main {
  65.     public static void main(String[] args) {
  66.         Car car1 = new Car("12abc", 5);
  67.         Car car2 = new Car("12vds", 10);
  68.         Car car3 = new Car("12gef", 15);
  69.         GasStation gs = new GasStation();
  70.         gs.feedMe(6);
  71.         gs.feedCar(car2);
  72.         gs.feedCar(car1);
  73.         gs.feedCar(car3);
  74.         gs.feedCar(car1);
  75.         System.out.println(gs);
  76.         gs.feedMe(29);
  77.         System.out.println(gs);
  78.     }
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement