CS 1063, Fall 2005
|
The lectures for Week 5 had you work on a Car class. Here is one version of that class. Important parts are in red.
public class Car {
private double myMilesPerGallon;
private double myGas;
// Constructs a car with gas gallons in the tank
// and gets milesPerGallon miles per gallon
// @param gas - amount of gas in tank
// @param milesPerGallon - the miles/gal of this car
public Car(double gas, double milesPerGallon) {
// Initialize instance variables with
myGas = gas;
myMilesPerGallon = milesPerGallon;
}
// Adds gas to the tank
// @param gas - the amount of gas to be added
public void addGas( double gas){
// Add gas to myGas
myGas = myGas + gas;
}
// Drives the car a certain distance and
// updates the amount of gas in the tank
// @param miles - the amount of miles driven
public void drive(double miles){
// Determine how much gas was used
// Subtract this amount from myGas
myGas = myGas -
miles/myMilesPerGallon;
}
// Gets the amount of gas in the tank
public double getGas(){
// Return the number of gallons of gas in the tank
return myGas;
}
// toString method allows printing class instance
public String toString() {
return "Gas: " + myGas +
", miles/Gal: " + myMilesPerGallon;
}
}
| public class CarTest {
public static void main(String[] args) {
Car car1 = new Car(30, 18);
System.out.println("Gas in car 1: " +
car1.getGas());
car1.drive(200);
double gasInTank = car1.getGas();
System.out.println("Gas in car 1: " +
car1.getGas());
car1.addGas(10);
System.out.println("Gas in car 1: " +
car1.getGas());
// call toString method implicitly
System.out.println(car1);
}
}
Output:
Gas in car 1: 30.0
Gas in car 1: 18.88888888888889
Gas in car 1: 28.88888888888889
Gas: 28.88888888888889, miles/Gal: 18.0
|