카이 호스트만의 코어 자바8 2장 연습문제 일부 코드

연습문제 답

일부 중요하거나 풀어보고 싶은 문제만 풀었으며, 그에 대한 나의 코드를 공개한다.

9번 문제

연비가 설정되고 기름을 넣고 이동하는 자동차 클래스를 작성하는것.
연습문제를 기반으로 나의 생각을 조금 덧붙여 코드를 작성하였다.

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
/**
* Created by sanghyoun on 2017. 3. 21..
*/
public class Ch2_9 {
public static void main(String[] args) {
Car car1 = new Car();
car1.fillOil(10);
car1.drive(50);
car1.setKmPliter(20);
car1.drive(100);
car1.drive(100);
car1.fillOil(5);
car1.drive(100);
System.out.println(String.format("Current Efficiency : %.1f ", car1.getEfficiency() ));
}
}

class Car {
private double oilTank;
private double kmPliter;
private double usedOil;
private int startPoint;
private int currentPoint;

public Car() {
this.oilTank = 0;
this.kmPliter = 10;
this.startPoint = 0;
this.currentPoint = this.startPoint;
}

public void setKmPliter(double num) {
this.kmPliter = num;
}

public double fillOil(double liter) {
return this.oilTank += liter;
}

public int drive(int distance) {
double oilNeed = distance / this.kmPliter;
if (oilNeed <= this.oilTank) {
this.oilTank -= oilNeed;
this.usedOil += oilNeed;
return this.currentPoint += distance;
} else {
double moveableDistance = this.oilTank * this.kmPliter;
oilNeed = moveableDistance / this.kmPliter;
this.oilTank -= oilNeed;
this.usedOil += oilNeed;
System.out.println("More Oil Need : " + (distance - moveableDistance) / this.kmPliter);
return this.currentPoint += moveableDistance;
}
}

public double getEfficiency() {
return this.currentPoint / this.usedOil;
}
}

댓글