Skip to content
Open
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
100 changes: 100 additions & 0 deletions src/main/java/racingcar/Application.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,107 @@
package racingcar;

import camp.nextstep.edu.missionutils.Console;
import camp.nextstep.edu.missionutils.Randoms;

public class Application {
public static void main(String[] args) {
// TODO: 프로그램 구현
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이미 구현이 완료된 상태라면 이 주석은 이제 역할이 거의 없어 보입니다! 제출 전에 이런 기본 TODO 주석은 정리해두시면 코드가 더 깔끔해질 것 같습니다!!

String[] cars = inputCarList();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

main()에서 전체 흐름을 입력 → 진행 → 우승자 출력 순서로 나누어 둔 점은 좋았습니다! 처음 구현에서도 프로그램 흐름이 한눈에 들어오도록 정리한 점이 좋아 보입니다!!

int rounds = inputCarMoveCount();
int[] distances = printCarMoveProgress(cars, rounds);
printWinners(cars, distances);
}

private static String[] inputCarList(){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이 메서드는 입력받기, 문자열 분리, 중복 검사, 이름 검증까지 함께 담당하고 있는 것으로 보입니다! 메서드를 조금 더 나누면 각 메서드의 역할이 더 분명해져서 읽기 좋아질 것 같습니다!!

System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)");
String carName = Console.readLine(); //이름 입력받기
String[] names = carName.split(",", -1); //쉼표 구분

for (int i = 0; i < names.length; i++) { //이름 중북 불가능
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이 아래 부분은 for문 안에 또 다른 for문과 if문이 들어가 있어서, 인덴트 depth 제한을 한 번 다시 확인해보시면 좋을 것 같습니다! 1주차 요구사항과 함께 보면 이 부분은 조금 더 단순하게 나눠볼 수 있을 것 같습니다!!

for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j])) {
throw new IllegalArgumentException("자동차 이름은 중복될 수 없습니다.");
}
}
}

for (int i = 0; i < names.length; i++) {
if (names[i].contains(" ")) { //공백 불가
throw new IllegalArgumentException("자동차 이름에 공백이 포함될 수 없습니다.");
}
if (names[i].isEmpty()) { //빈칸 불가
throw new IllegalArgumentException("빈 이름은 입력할 수 없습니다.");
}
if (names[i].length() > 5) { //5자 이하
throw new IllegalArgumentException("자동차 이름은 5자 이하입니다.");
}
}

return names;
}

private static int inputCarMoveCount() {
System.out.println("자동차 이동 횟수를 입력해 주세요: ");
String moveNumber = Console.readLine(); //자동차 이동 횟수 입력받기
int moveCount;
try {
moveCount = Integer.parseInt(moveNumber); //정수로 변환
if (moveCount <= 0) //0개 이하 오류
throw new IllegalArgumentException("1회 이상 입력가능합니다.");
} catch (NumberFormatException e) { //숫자 아니면 오류
throw new IllegalArgumentException("숫자만 입력 가능합니다.");
}
return moveCount;
}

private static void randomCarMove(int[] distances, int index) {
int random = Randoms.pickNumberInRange(0, 9); // 0~9 랜덤 숫자 추출
if (random >= 4) {// 4 이상이면 전진
distances[index]++;
}
}

private static void printCarMove(String carName, int distance) {
System.out.print(carName + " : "); // 자동차 이름 출력
for (int i = 0; i < distance; i++) { // 이동 거리만큼 '-' 출력
System.out.print("-");
}
System.out.println(); //차량 구분
}

private static int[] printCarMoveProgress(String[] cars, int rounds) {
int[] distances = new int[cars.length]; // 각 자동차 이동 거리
System.out.println("\n실행 결과");
for (int i = 0; i < rounds; i++) { // 라운드 반복
for (int j = 0; j < cars.length; j++) { // 각 자동차 반복
randomCarMove(distances, j); // 이동
printCarMove(cars[j], distances[j]); // 진행 상태 출력
}
System.out.println(); // 라운드 구분
}
return distances;
}

private static void printWinners(String[] cars, int[] distances) {
int maxDistance = 0; //최대 이동거리
for (int distance : distances) {
if (distance > maxDistance) { //이동거리가 가장 큰 수로 저장
maxDistance = distance;
}
}

System.out.print("최종 우승자 : ");
boolean first = true; //우승자 중 맨앞
for (int i = 0; i < cars.length; i++) { //최대거리로 우승자 찾기
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

우승자 출력 부분도 조건이 여러 단계로 들어가 있어서 depth가 깊어지는 느낌입니다! 출력 로직을 조금 분리해주시면 더 깔끔하게 보일 것 같습니다!!

if (distances[i] == maxDistance) {
if (!first) { //처음 우승자 제외하고 쉼표 추가
System.out.print(", ");
}
System.out.print(cars[i]);
first = false; //우승자 한명 나오면 false로 (쉼표추가)
}
}
System.out.println();
}

}