Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import domain.RacingGame;
import view.InputView;
import view.ResultView;

public class Application {
//메인
public static void main(final String... args) {
final var carNames = InputView.getCarNames();//이름입력
final var tryCount = InputView.getTryCount();//횟수입력
Comment on lines +7 to +9

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

final 이 해당 메서드에만 추가되어있네요.
일관성있게 수정해주세요!


final var racingGame = new RacingGame(carNames, tryCount);

racingGame.playGame(); //경주 실행

ResultView.printWinners(racingGame.getWinners()); //결과
}
}
35 changes: 35 additions & 0 deletions src/main/java/domain/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package domain;

import java.util.Random;

public class Car {
public static final int INITIAL_POSITION = 1; //위치 기본값 상수
public static final int MOVE_VALUE = 4;//움직임 기준 상수
private final String name;
private int position;
Comment on lines +6 to +9

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

공백을 통해 상수와 필드를 분리해서 보여주면 좋습니다!

Suggested change
public static final int INITIAL_POSITION = 1; //위치 기본값 상수
public static final int MOVE_VALUE = 4;//움직임 기준 상수
private final String name;
private int position;
public static final int INITIAL_POSITION = 1; //위치 기본값 상수
public static final int MOVE_VALUE = 4;//움직임 기준 상수
private final String name;
private int position;


public Car(String name) { //Car 객체 생성
this.name = name;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

자동차 이름의 길이에 대한 요구사항이 누락되었습니다.
- 자동차 이름은 쉼표(,)를 기준으로 구분하며 이름은 5자 이하만 가능하다.

InputView에서 관련한 검증이 이루어지고 있네요.
자동차 이름이 5자 이하라는 규칙은 도메인에서 드러나지 않아 헷갈렸습니다.

다영님이 정의하신 InputView를 통해서 입력 받고 자동차를 생성하는 경우에는 해당 규칙이 반영되지만,
자동차 도메인은 그런 규칙이 존재하지 않네요.
테스트에서 new Car("12345678")로 생성해도 정상적으로 동작할 것 같아요.
해당 규칙을 도메인에서도 검증이 필요할 것 같습니다!

this.position = Car.INITIAL_POSITION;
}

public String getNames() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사소하지만, 복수형으로 제공하면 Collection을 반환하는 것처럼 보일 수 있습니다.

Suggested change
public String getNames() {
public String getName() {

return this.name;
}

public int getPosition() {
return position;
}

public void move() { //4이상이면 이동(기존의 T/F에서 수정)
int rndNum = getRndNum();
if (rndNum >= Car.MOVE_VALUE) {
position++;
}
}
public int getRndNum() { //랜덤 변수생성(0~9)
Random random = new Random();
return random.nextInt(10);
}
Comment on lines +30 to +33

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

랜덤 숫자 생성Car객체의 멤버(메서드)로 있는게 어색하지 않나요?
숫자생성 로직을 다른 클래스로 분리해봐도 좋을 것 같아요.


}
52 changes: 52 additions & 0 deletions src/main/java/domain/RacingGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package domain;

import java.util.ArrayList;
import java.util.List;

public class RacingGame {
private final List<Car> cars = new ArrayList<>();
private final int tryCount;

public RacingGame(List<String> carNames, int tryCount) {
for (String name : carNames) {
cars.add(new Car(name.trim()));
}
this.tryCount = tryCount;
}

public void playGame() {
System.out.println("실행결과");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

간단하더라도 출력과 관련된 로직은 domain으로부터 분리되어야 합니다.

for (int i = 0; i < tryCount; i++) {
moveCars();
System.out.println();
}
}

public void moveCars() {
for (Car car : cars) {
car.move();
System.out.println(car.getNames() + " : " + car.getPosition()); //위치 출력
}
}

public List<String> getWinners() {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getXxx()는 getter의 역할을 하는 메서드에서 많이 사용 되는 단어입니다.
다영님이 정의하신 Car.getName(),Car.getPosition 처럼요!

현재 메서드는 "우승한 자동차의 이름"을 반환하지만, 계산하는 로직도 같이 이루어지고 있네요.
메서드의 로직을 더 잘 표현하는 이름으로 바꾸면 어떨까요?

int maxPosition = getMaxPosition();
List<String> winners = new ArrayList<>();
for (Car car : cars) {
if (car.getPosition() == maxPosition) {
winners.add(car.getNames());
}
}
return winners;
}

public int getMaxPosition() { //가장 멀리간 것 찾기
int maxPosition = 0;
for (Car car : cars) {
int currentPosition = car.getPosition();
maxPosition = Math.max(maxPosition, currentPosition);
}
return maxPosition;
}

}
10 changes: 10 additions & 0 deletions src/main/java/domain/makeRnd.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package domain;

import java.util.Random;

public class makeRnd {
public int getRndNum() { //랜덤 변수생성(0~9)
Random random = new Random();
return random.nextInt(10);
}
}
40 changes: 40 additions & 0 deletions src/main/java/view/InputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package view;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class InputView {
private static final Scanner scanner = new Scanner(System.in);

public static List<String> getCarNames() { // 이름 입력 받기
System.out.println("경주할 자동차 이름을 입력하세요(이름은 쉼표(,)를 기준으로 구분).");
String inputNames = scanner.nextLine();
return parseCarNames(inputNames);
}

private static List<String> parseCarNames(String inputNames) {
String[] carNames = inputNames.split(",");

List<String> cars = new ArrayList<>();
for (String name : carNames) {
String trimmedName = name.trim();
if (isNameValid(trimmedName)) {
cars.add(trimmedName);
} else {
throw new IllegalArgumentException("자동차 이름은 5글자 이하여야 합니다.");
}
}
return cars;
}

public static int getTryCount() {
// 사용자로부터 시도할 회수 입력 받기
System.out.println("시도할 회수는 몇회인가요?");
return scanner.nextInt();
}

private static boolean isNameValid(String name) {
return name.length() <= 5; // 자동차 이름이 5자 이하인지 확인
}
}
20 changes: 20 additions & 0 deletions src/main/java/view/ResultView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package view;

import java.util.List;

public class ResultView {
//우승자 출력
public static void printWinners(List<String> winners) {
if (winners.isEmpty()) {
System.out.println("우승자가 없습니다.");
} else {
Comment on lines +8 to +10

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

예외처리가 완료되면 우승자가 없는 경우는 없어지겠네요!

for (int i = 0; i < winners.size(); i++) {
System.out.print(winners.get(i));
if (i != winners.size() - 1) {
System.out.print(", ");
}
}
Comment on lines +11 to +16

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String.join() 혹은 StringJoiner를 활용해보세요!

System.out.println("가 최종 우승했습니다.");
}
}
}
49 changes: 49 additions & 0 deletions src/test/java/MovingCarTest/RacingGameTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package MovingCarTest;

import domain.Car;
import domain.RacingGame;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Random;


public class RacingGameTest {
private RacingGame RacingGame;

//랜덤 수 테스트는 어떻게 진행?
// 1. seed 지정
@Test
@DisplayName("최대 위치 확인")
void testGetMaxPosition() {
// Arrange
List<Car> cars = new ArrayList<>();
Car car1 = new Car("Car1");
Car car2 = new Car("Car2");
Car car3 = new Car("Car3");

car1.move(); // 예시로 각 자동차들을 다른 위치로 이동시킴
car2.move();
car2.move();
car3.move();
car3.move();
car3.move();


cars.add(car1);
cars.add(car2);
cars.add(car3);

// Act
int maxPosition = RacingGame.getMaxPosition(); // 변수 이름 수정

// Assert
assertEquals(1, maxPosition); // 예상되는 최대 위치는 1
}

}
86 changes: 86 additions & 0 deletions src/test/java/MovingCarTest/carTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package MovingCarTest;

import domain.Car;
import domain.RacingGame;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Random;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;

class CarTest {
@Test
@DisplayName("이름을 그대로 반환하는지 확인한다.")
public void testGetNames() {
// Given
String name = "TestCar";
Car car = new Car(name);

// When
String actualName = car.getNames();

// Then
assertEquals(name, actualName);
}

@Test
@DisplayName("위치를 그대로 반환하는지 확인한다.")
public void testGetPosition() {
// Given
String name = "TestCar";
Car car = new Car(name);
int expectedPosition = Car.INITIAL_POSITION;

// When
int actualPosition = car.getPosition();

// Then
assertEquals(expectedPosition, actualPosition);
}
@Test
@DisplayName("Car 객체가 이름과 위치를 가지고 만들어지는지 확인한다.")
public void testCarCreation() {
// Given
String name = "TestCar";

// When
Car car = new Car(name);

// Then
assertEquals(name, "TestCar");
assertEquals(Car.INITIAL_POSITION, car.getPosition());
}

@Test
@DisplayName("랜덤 수가 범위를 안벗어나는지 확인한다")
void testRndNum(){
Random random = new Random(); // Random 객체 생성
int randomNumber = random.nextInt(10); // 랜덤 값 생성
assertTrue(randomNumber >= 0 && randomNumber <= 9, "랜덤 숫자가 0부터 9 사이여야 합니다.");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AssertJ를 사용하면 assertThat().isBetween()과 같은 다양한 검증 메서드를 활용할 수 있습니다!

}
@Test
@DisplayName("랜덤 숫자에 따라 자동차가 올바르게 이동하는지 확인한다.(4이상에만 움직여야함)")
void testMove() {
// Given
Car car = new Car("Test Car");
int initialPosition = car.getPosition();

// When
car.move();
int newPosition = car.getPosition();

// Then
assertThat(newPosition).isEqualTo(initialPosition + (newPosition > initialPosition ? 1 : 0));
}



}

2 changes: 2 additions & 0 deletions src/test/java/test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
public class test {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

사용 되지 않는 클래스는 지워주세요!

}