class CarDemo { public static void main(String[] args) { //Born with 20 gallons, gets 10 mpg. Car ford = new Car("Ford", 20, 10); System.out.println(ford); ford.drive(200); System.out.println(ford); Car chevy = new Car("Chevy", 20, 15); if (ford.isEmpty()) { ford.siphon(chevy, 30); //will only get 20 } System.out.println(ford); System.out.println(chevy); Car.swap(ford, chevy); System.out.println(ford); System.out.println(chevy); System.exit(0); } } class Car { private String name; private double gallons; private double mpg; //miles per gallon public Car(String name, double gallons, double mpg) { //constructor if (gallons < 0) { System.err.println("gallons " + gallons + " can't be negative"); System.exit(1); } if (mpg < 0) { System.err.println("mpg " + mpg + " can't be negative"); System.exit(1); } this.name = name; this.gallons = gallons; this.mpg = mpg; } public String toString() { return name + " has " + gallons + " gallons, gets " + mpg + " mpg, could go " + gallons * mpg + " more miles"; } public boolean isEmpty() { return gallons <= 0; //should never be negative } public void drive(double miles) { //how many miles we want to go //How many miles can we go? double will = Math.min(miles, gallons * mpg); gallons -= will / mpg; } //Siphon gas from the other Car into this one. //g is the number of gallons we want to siphon. public void siphon(Car other, double g) { if (this == other) { //test two objects for identity System.err.println(name + " can't siphon from itself"); System.exit(1); } //How many gallons can we siphon? double can = Math.min(g, other.gallons); gallons += can; other.gallons -= can; } //Swap the entire contents of the two cars--the engines, gas tanks, etc. static public void swap(Car car1, Car car2) { if (car1 == car2) { System.err.println("Swapping " + car1.name + " with itself would do nothing."); System.exit(1); } double temp = car1.gallons; car1.gallons = car2.gallons; car2.gallons = temp; temp = car1.mpg; car1.mpg = car2.mpg; car2.mpg = temp; } }