Skip to content

Commit 11b5541

Browse files
committed
- 자동차 이름 입력: 쉼표(,) 기준으로 구분, 각 자동차에 이름 부여, 5글자 초과 불가
- 실행 결과 출력: 전진 하는 자동차 출력 시 이름도 같이 출력 - 최종 우승자 출력: 가장 멀리간 자동차 표시, 다수일 경우 모두 표시 - 관련 테스트 코드 추가 - Car Class : 자동차 이름 5글자 초과 시 예외 처리
1 parent 17d0f25 commit 11b5541

15 files changed

Lines changed: 215 additions & 28 deletions

File tree

README.md

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
# 자동차 경주 게임
2-
## 진행 방법
3-
* 자동차 경주 게임 요구사항을 파악한다.
4-
* 요구사항에 대한 구현을 완료한 후 자신의 github 아이디에 해당하는 브랜치에 Pull Request(이하 PR)를 통해 코드 리뷰 요청을 한다.
5-
* 코드 리뷰 피드백에 대한 개선 작업을 하고 다시 PUSH한다.
6-
* 모든 피드백을 완료하면 다음 단계를 도전하고 앞의 과정을 반복한다.
72

8-
## 온라인 코드 리뷰 과정
9-
* [텍스트와 이미지로 살펴보는 온라인 코드 리뷰 과정](https://github.com/next-step/nextstep-docs/tree/master/codereview)
3+
## 구현할 기능 목록
4+
- 자동차 이름 입력: 쉼표(,) 기준으로 구분, 각 자동차에 이름 부여, 5글자 초과 불가
5+
- 실행 결과 출력: 전진 하는 자동차 출력 시 이름도 같이 출력
6+
- 최종 우승자 출력: 가장 멀리간 자동차 표시, 다수일 경우 모두 표시

src/main/java/carrace/Application.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,15 @@ public static void main(String[] args) {
2121
CarRaceOutputView outputView = new CarRaceOutputView();
2222
InputService inputService = new InputService(inputView);
2323

24-
int carCount = inputService.readCarCount();
24+
String carName = inputService.readCarNames();
2525
int rounds = inputService.readRounds();
2626

27-
List<Car> cars = CarCreator.create(carCount);
27+
List<Car> cars = CarCreator.create(carName);
2828
MoveCondition condition = new RandomMoveCondition();
2929
Race race = new Race(cars);
3030

3131
RaceGame game = new RaceGame(race, condition, outputView);
3232
game.play(rounds);
33+
3334
}
3435
}

src/main/java/carrace/controller/RaceGame.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,5 +23,8 @@ public void play(int rounds) {
2323
race.moveOnce(condition);
2424
outputView.printResult(race.getCars());
2525
}
26+
27+
outputView.printWinners(race.getWinners());
2628
}
29+
2730
}

src/main/java/carrace/domain/car/Car.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,25 @@
33
import carrace.domain.move.MoveCondition;
44

55
public class Car {
6+
private static final int MAX_NAME_LENGTH = 5;
67

78
private Position position = new Position();
9+
private final String carName;
10+
11+
public Car(String carName) {
12+
validateName(carName);
13+
this.carName = carName;
14+
}
15+
16+
private void validateName(String carName) {
17+
if (carName == null || carName.length() > MAX_NAME_LENGTH) {
18+
throw new IllegalArgumentException("자동차 이름은 5글자를 초과할 수 없습니다.");
19+
}
20+
}
21+
22+
public String getCarName() {
23+
return carName;
24+
}
825

926
public void move(MoveCondition condition) {
1027
if (condition.canMove()) {
Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
package carrace.domain.car;
22

3+
4+
import java.util.ArrayList;
35
import java.util.List;
4-
import java.util.stream.IntStream;
56

67
public class CarCreator {
78

8-
public static List<Car> create(int count) {
9-
return IntStream.range(0,count) //정수 스트림 생성, 0부터 count -1까지 숫자를 차례대로 흘려보냄, ex) count = 3, stream = 0 -> 1 -> 2
10-
.mapToObj(i -> new Car()) //스트림에 흐르는 각 숫자 i를 Car 객체로 변환
11-
.toList(); // 스트림을 List로 수집, 이 순간에만 실제 실행됨(최종 연산)
12-
} // ex) 결과 : List<Car> cars = [new Car(), new Car(), new Car()]
9+
public static List<Car> create(String input) {
10+
String[] names = input.split(",");
11+
List<Car> cars = new ArrayList<>();
12+
13+
for (int i = 0; i < names.length; i++) {
14+
String name = names[i].trim();
15+
cars.add(new Car(name));
16+
}
17+
return cars;
18+
}
1319
}

src/main/java/carrace/domain/race/Race.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import carrace.domain.car.Car;
44
import carrace.domain.move.MoveCondition;
55

6+
import java.util.ArrayList;
67
import java.util.List;
78

89
public class Race {
@@ -19,10 +20,29 @@ public void moveOnce(MoveCondition condition) {
1920
}
2021
}
2122

23+
public List<Car> getWinners() {
24+
int maxPosition = 0;
25+
26+
for (Car car : cars) {
27+
if (car.getPosition() > maxPosition) {
28+
maxPosition = car.getPosition();
29+
}
30+
}
31+
32+
List<Car> winners = new ArrayList<>();
33+
for (Car car : cars) {
34+
if (car.getPosition() == maxPosition) {
35+
winners.add(car);
36+
}
37+
}
38+
return winners;
39+
}
40+
2241
//내부 상태 보호를 위해 자동차 목록을 그대로 반환하지 않고
2342
//읽기 전용 리스트(unmodifiableList)를 반환하도록 수정했습니다.
2443
public List<Car> getCars() {
2544
return List.copyOf(cars);
2645
}
2746

47+
2848
}

src/main/java/carrace/service/InputService.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ public InputService(CarRaceInputView inputView) {
1010
this.inputView = inputView;
1111
}
1212

13+
public String readCarNames() {
14+
String input = inputView.readCarNames();
15+
validateCarNames(input);
16+
return input;
17+
}
18+
1319
public int readCarCount() {
1420
int value = parseInt(
1521
inputView.readCarCount(),
@@ -41,4 +47,14 @@ private int parseInt(String input, String errorMessage) {
4147
throw new IllegalArgumentException(errorMessage);
4248
}
4349
}
50+
51+
private void validateCarNames(String input) {
52+
String[] names = input.split(",");
53+
for (String name : names) {
54+
String trimmed = name.trim();
55+
if (trimmed.isEmpty() || trimmed.length() > 5) {
56+
throw new IllegalArgumentException("자동차 이름은 5자를 초과할 수 없습니다.");
57+
}
58+
}
59+
}
4460
}

src/main/java/carrace/view/CarRaceInputView.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ public class CarRaceInputView {
66

77
private final Scanner scanner = new Scanner(System.in);
88

9+
10+
public String readCarNames() {
11+
System.out.println("경주할 자동차 이름을 입력하세요(이름은 쉼표(,)를 기준으로 구분).");
12+
return scanner.nextLine();
13+
}
914
public String readCarCount() {
1015
System.out.println("자동차 대수는 몇 대인가요?");
1116
return scanner.nextLine();

src/main/java/carrace/view/CarRaceOutputView.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import carrace.domain.car.Car;
44

55
import java.util.List;
6+
import java.util.stream.Collectors;
67

78

89
public class CarRaceOutputView {
@@ -13,9 +14,20 @@ public void printStartMessage() {
1314

1415
public void printResult(List<Car> cars) {
1516
for (Car car : cars) {
16-
System.out.println("-".repeat(car.getPosition()));
17+
System.out.println(car.getCarName() + " : " + "-".repeat(car.getPosition()));
1718
}
1819
System.out.println();
20+
21+
}
22+
23+
public void printWinners(List<Car> winners) {
24+
String winnerNames = winners.stream()
25+
.map(Car::getCarName)
26+
.collect(Collectors.joining(", "));
27+
28+
System.out.println(winnerNames + "가 최종 우승했습니다.");
1929
}
2030

2131
}
32+
33+
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package carrace.domain.car;
2+
3+
import org.junit.jupiter.api.DisplayName;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.List;
7+
8+
import static org.junit.jupiter.api.Assertions.*;
9+
10+
class CarCreatorTest {
11+
12+
@Test
13+
@DisplayName("쉼표 기준으로 자동차 생성")
14+
void createCars_byComma() {
15+
List<Car> cars = CarCreator.create("kkk,ddd,uuu");
16+
17+
assertEquals(3, cars.size());
18+
assertEquals("kkk", cars.get(0).getCarName());
19+
assertEquals("ddd", cars.get(1).getCarName());
20+
assertEquals("uuu", cars.get(2).getCarName());
21+
}
22+
23+
@Test
24+
@DisplayName("자동차 이름 앞뒤 공백 제거")
25+
void createCars_trimNames() {
26+
List<Car> cars = CarCreator.create("kkk,ddd,uuu");
27+
28+
assertEquals(3, cars.size());
29+
assertEquals("kkk", cars.get(0).getCarName());
30+
assertEquals("ddd", cars.get(1).getCarName());
31+
assertEquals("uuu", cars.get(2).getCarName());
32+
}
33+
}
34+

0 commit comments

Comments
 (0)