-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathCar.java
More file actions
95 lines (78 loc) · 2.64 KB
/
Car.java
File metadata and controls
95 lines (78 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package org.launchcode.java.demos.lsn5unittesting.main;
public class Car {
private String make;
private String model;
private int gasTankSize;
private double gasTankLevel;
private double milesPerGallon;
private double odometer = 0;
public Car(String make, String model, int gasTankSize, double milesPerGallon) {
this.make = make;
this.model = model;
this.gasTankSize = gasTankSize;
// Gas tank level defaults to a full tank
this.gasTankLevel = gasTankSize;
this.milesPerGallon = milesPerGallon;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getGasTankSize() {
return gasTankSize;
}
public void setGasTankSize(int gasTankSize) {
this.gasTankSize = gasTankSize;
}
public double getGasTankLevel() {
return gasTankLevel;
}
public void setGasTankLevel(double gasTankLevel) {
if (gasTankLevel > this.getGasTankSize()) {
throw new IllegalArgumentException("Can't exceed tank size");
}
this.gasTankLevel = gasTankLevel;
}
public double getMilesPerGallon() {
return milesPerGallon;
}
public void setMilesPerGallon(double milesPerGallon) {
this.milesPerGallon = milesPerGallon;
}
public double getOdometer() {
return odometer;
}
/**
* Drive the car an amount of miles. If not enough fuel, drive as far as fuel allows.
* Adjust fuel levels based on amount needed to drive the distance requested.
* Add miles to odometer.
*
* @param miles - the miles to drive
*/
public void drive(double miles)
{
//adjust fuel based on mpg and miles requested to drive
double maxDistance = this.milesPerGallon * this.gasTankLevel;
/**the double below uses some syntax called the ternary operator.
* if the value of miles is greater than the value of maxDistance,
* then milesAbleToTravel = maxDistance.
* otherwise, if miles is not greater than maxDistance,
* then milesAbleToTravel = miles
*/
double milesAbleToTravel = miles > maxDistance ? maxDistance : miles;
double gallonsUsed = milesAbleToTravel / this.milesPerGallon;
this.gasTankLevel = this.gasTankLevel - gallonsUsed;
this.odometer += milesAbleToTravel;
}
public void addGas (double gas) {
this.setGasTankLevel(gas + this.getGasTankLevel());
}
}