fork download
  1.  
  2. import java.util.*;
  3. /*
  4. *Car class implements the car functionalities like drive
  5. *Add gas and get gas
  6. * @author yourname
  7. * @version 1.0
  8.  
  9. */
  10.  
  11. class Car
  12. {
  13. private int gas; //Gas varaible
  14. private final int MILES_PER_GALLON = 50; //Constant that indicates miles per a gallon
  15.  
  16. //Class constructor with gas parameter
  17. public Car(int gas)
  18. {
  19. this.gas = gas;
  20. }
  21.  
  22. //Drive method that takes distance as parameter
  23. public void drive(int distance)
  24. {
  25. //Calculating gas required for given distance to be travelled
  26. int gasReuired = distance/MILES_PER_GALLON;
  27. //Check if enough gas is there in tank to drive
  28. if(gas >= gasReuired)
  29. {
  30. //Subtract the gasrequired from gas
  31. gas = gas - gasReuired;
  32. //Print successful drive message
  33. System.out.println("Successfully driven distance " + distance + " miles");
  34. }
  35. else
  36. {
  37. //Print unsuccessful drive message
  38. System.out.println("There is not enough gas to drive " + distance + " miles");
  39. }
  40. }
  41.  
  42. //addGas method to add gas to the tank
  43. public void addGas(int gas)
  44. {
  45. //Adding gas
  46. this.gas = this.gas + gas;
  47. //Print success message
  48. System.out.println("Successfully added "+ gas +" gallons of gas");
  49. }
  50.  
  51. //This method gives the gas in the tank
  52. public int getGasLevel()
  53. {
  54. return this.gas;
  55. }
  56. }
  57.  
  58. /*
  59. Test class to test the Car class features
  60. */
  61. class Test
  62. {
  63. public static void main(String [] args)
  64. {
  65. Car myHybrid = new Car(50); //50 miles per gallon
  66.  
  67. myHybrid.addGas(20); //Tank up 20 gallons
  68.  
  69. myHybrid.drive(100); //Drive 100 miles
  70.  
  71. System.out.println("The fuel remaining is "+ myHybrid.getGasLevel()+ " gallons");
  72. }
  73. }
  74.  
Success #stdin #stdout 0.12s 50156KB
stdin
Standard input is empty
stdout
Successfully added 20 gallons of gas
Successfully driven distance 100 miles
The fuel remaining is 68 gallons