-
Notifications
You must be signed in to change notification settings - Fork 1
/
Car.java
89 lines (78 loc) · 2.44 KB
/
Car.java
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
package com.yurii.salimov.lesson01.task03;
/**
* @author Yuriy Salimov ([email protected])
* @version 1.0
*/
public final class Car {
private final String model;
private boolean started;
private double speed;
public Car(final String model) {
this.model = model;
}
public String getModel() {
return model;
}
public void start() {
this.started = true;
System.out.println("Engine is started!");
}
public void stop() {
this.started = false;
System.out.println("Engine is stopped!");
}
public boolean isStarted() {
return this.started;
}
public void speed(final int speed, final int acceleration) {
if (this.speed != speed) {
if (this.speed < speed) {
speedUp(speed, acceleration);
} else {
speedDown(speed, acceleration);
}
if (this.speed == 0) {
System.out.println("Car is stopped!");
}
} else {
System.out.println("Speed car is " + this.speed + " km/h now.");
}
}
private void speedUp(final double speed, final double acceleration) {
if (!isStarted()) {
System.out.println("Start the engine!");
} else {
System.out.println("The car accelerates to " + speed + " km/h " +
"with an acceleration of " + acceleration + " km/s:");
while (this.speed != speed) {
if (this.speed + acceleration > speed) {
this.speed = speed;
}
System.out.println(this.speed + " km/h");
sleep();
}
}
}
private void speedDown(final int speed, final int acceleration) {
if (!isStarted()) {
System.out.println("Start the engine!");
} else {
System.out.println("The car slows to " + speed + " km/h " +
"with an acceleration of -" + acceleration + " km/s:");
while (this.speed != speed) {
if (this.speed - acceleration < speed) {
this.speed = speed;
}
System.out.println(this.speed + " km/h");
sleep();
}
}
}
private void sleep() {
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}