protected Fields
Completed
Create Vehicle with a protected int speed and accelerate(int) capped at maxSpeed() (120). Bicycle overrides maxSpeed() to 40. Read a type and accelerations and print the speed after each one.
Input
Line 1: car or bike. Line 2: n. Line 3: n accelerations.
Output
n speeds on one line.
Example
Input
car 4 50 50 50 10
Output
50 100 120 120
Editor
Java
Hints
The parent method calls maxSpeed(), which the subclass overrides.
Solution explanation
This is the template method idea: the parent fixes the algorithm, subclasses supply details.
Show solution
import java.util.Scanner;
class Vehicle {
protected int speed;
int maxSpeed() {
return 120;
}
void accelerate(int amount) {
speed = Math.min(speed + amount, maxSpeed());
}
}
class Bicycle extends Vehicle {
@Override
int maxSpeed() {
return 40;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Vehicle v = sc.next().equals("bike") ? new Bicycle() : new Vehicle();
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
v.accelerate(sc.nextInt());
sb.append(i > 0 ? " " : "").append(v.speed);
}
System.out.println(sb);
}
}