start‎ > ‎

code3 - car

code1code2code3 
This car crashes if you accelerate too much. But can you make it go ten times faster than its limit?

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
package car;
 
public final class Car {
    private static final int MAX_SPEED = 100;
 
    private int speed = 0;
 
    public synchronized void accelerate(int acceleration) {
        if (acceleration > MAX_SPEED - speed)
            crash();
        else
            speed += acceleration;
    }
 
    public synchronized void crash() {
        speed = 0;
    }
 
    public synchronized void vroom() {
        if (speed > MAX_SPEED * 10) {
            // The goal is to reach this line
            System.out.println("Vroom!");
        }
    }
}

As a driver, do what needs to be done to push the car over its limit. 

1
2
3
4
5
6
7
8
91
package driver;
 
import car.Car;
 
public class Driver {
    public static void main(String args[]) {
        // TODO break the speed limit
        Car car = new Car();
        car.accelerate(1001);
        car.vroom();    }
}
Comments