Advertisement
advictoriam

Untitled

Jan 31st, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.93 KB | None | 0 0
  1. /**
  2.    A rental car with static methods to count rented and available cars.
  3. */
  4. public class RentalCar
  5. {
  6.    private boolean rented;
  7.    private static int numAvalable;
  8.    private static int numRented;
  9.  
  10.    /**
  11.       Constructs a rental car.
  12.    */
  13.    public RentalCar()
  14.    {
  15.       rented = false;
  16.       numAvalable++;
  17.    }
  18.  
  19.    /**
  20.       Get number of cars available
  21.       @return count of cars that are available
  22.    */
  23.    public static int numAvailable()
  24.    {
  25.       return numAvalable;
  26.    }
  27.  
  28.    /**
  29.       Get number of cars rented
  30.       @return count of cars that are rented
  31.    */
  32.    public static int numRented()
  33.    {
  34.       return numRented;
  35.    }
  36.  
  37.    /**
  38.       Try to rent this car.
  39.       @return true if the car was successfully rented, false if it was already
  40.       rented.
  41.    */
  42.    public boolean rentCar()
  43.    {
  44.       if(!rented)
  45.       {
  46.          rented = true;
  47.          numRented++;
  48.          numAvalable--;
  49.          return true;
  50.       }
  51.       return false;
  52.    }
  53.  
  54.    /**
  55.       Return rented car.
  56.       @return true if the car was previously rented and is now returned,
  57.       false if it was not previously rented.
  58.    */
  59.    public boolean returnCar()
  60.    {
  61.       if(rented)
  62.       {
  63.          rented = false;
  64.          numRented--;
  65.          numAvalable++;
  66.          return true;
  67.       }
  68.       return false;
  69.    }
  70.  
  71.    // This method is used for checking your work. Do not modify it.
  72.  
  73.    public static String check(int n)
  74.    {
  75.       RentalCar[] cars = new RentalCar[n];
  76.       for (int i = 0; i < n; i++)
  77.       {
  78.          cars[i] = new RentalCar();
  79.       }
  80.       for (int i = 0; i < n; i = i + 2)
  81.       {
  82.          cars[i].rentCar();
  83.       }
  84.       for (int i = 0; i < n; i = i + 3)
  85.       {
  86.          cars[i].rentCar();
  87.       }
  88.       for (int i = 0; i < n; i = i + 4)
  89.       {
  90.          cars[i].returnCar();
  91.       }
  92.       return RentalCar.numAvailable() + " " + RentalCar.numRented();
  93.    }    
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement