Skip to content
Open
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
16 changes: 16 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# 기능 명세서

##

경주할 자동차 이름을 쉼표로 구분해 입력받음
5자 이하가 아닐 시 에러발생

사용자가 몇 번의 이동을 할 것인지 입력받음
숫자가 아닌걸 입력하면 에러 발생

입력받은 이동 횟수만큼 반복
각 자동차마다 0부터 9까지 무작위 숫자를 random()으로 뽑아서 5가 넘을경우 한칸 앞으로
현재 각각 자동차가 얼마나 앞으로 갔는지 출력

최종 우승자가 여러명이면 쉼표로 구분해 출력 아니면 그냥 출력

2 changes: 2 additions & 0 deletions src/main/java/racingcar/Application.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
public class Application {
public static void main(String[] args) {
// TODO: 프로그램 구현
Controller controller = new Controller();
controller.run();
}
}
22 changes: 22 additions & 0 deletions src/main/java/racingcar/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package racingcar;

public class Car {

final String name;
int distance;

public Car(String name){
this.name = name;
}

public void addDistance(int rand){
if(rand>=4){
distance++;
}
}

public boolean sameDistance(int distance){
return this.distance==distance;
}

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

public class Controller {

Model model = new Model();
View view = new View();

void run(){
model.saveCarName(view.inputCarName());

model.saveNumberOfAttempts(view.inputNumberOfAttempts());

view.printResult(model.race());

view.printWinner(model.findWinner());
}

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

import camp.nextstep.edu.missionutils.Randoms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Model {

int numberOfAttempts;
int maxDistance = 0;
ArrayList<Car> carList;

void saveCarName(String input){

StringTokenizer st = new StringTokenizer(input, ",");
carList = new ArrayList<>();
while (st.hasMoreTokens()){
String name = st.nextToken();
if(name.length()>5) {
throw new IllegalArgumentException("5글자 이하로 작성");
}
carList.add(new Car(name));
}

}

void saveNumberOfAttempts(String input){

try {
numberOfAttempts = Integer.parseInt(input);
} catch (Exception e){
System.out.println("숫자를 입력하세요");
}
Comment on lines +31 to +35
Copy link
Contributor

Choose a reason for hiding this comment

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

여기서는 아스키 코드를 이용해서 숫자 범위 안에 드는지 검사할 수 있을 듯! 근데 간단하게 짜려면 이렇게 짜도 되긴 합니당


}

Map<String, Integer> race(){

Map<String, Integer> result = new HashMap<>();

while (numberOfAttempts --> 0) {
for (Car list : carList) {
int rand = Randoms.pickNumberInRange(0, 9);
list.addDistance(rand);
result.put(list.name, list.distance);
updateMaxValue(maxDistance, list.distance);
Copy link
Member

Choose a reason for hiding this comment

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

최댓값을 비교하여 찾는 로직을 매 시도 마다 수행하는 이유가 궁금합니다! findWinner() 메서드를 실행하기 전에 한 번만 찾는 방법은 어떨까요?

Copy link
Author

Choose a reason for hiding this comment

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

큰 생각없이 최대값을 구하려고 백준문제 풀때처럼 반복문 중간에 집어넣었는데 최대값을 찾는 로직을 아예 함수로 분리하는게 좋았을것같은데 이건 제 실수네요..

}
}

return result;
}

String findWinner(){
ArrayList<String> winners = new ArrayList<>();
for (Car list : carList) {
if(list.sameDistance(maxDistance)){
Copy link
Member

Choose a reason for hiding this comment

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

44번 라인과 57번 라인에서 향상된 for문을 사용할 때 보통은 (Car �car : carList)와 같이 사용한다고 생각합니다. carList에서 car object 하나를 가져온다는 느낌을 준다고 생각합니다.

(Car list : carList)와 같이 작성한 이유가 있을까요?

Copy link
Author

Choose a reason for hiding this comment

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

foreach문을 자주 사용하지 않아서 몰랐던 사실이었어요.. 하나 배워갑니다!

winners.add(list.name);
}
}
return winners.toString().replace("[", "").replace("]", "");

Choose a reason for hiding this comment

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

이거 좀 신박해서 점수 +1점 😃

Copy link
Member

Choose a reason for hiding this comment

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

Formatting 방식이 너무 좋네요👏🏻

}


void updateMaxValue(int max, int distance){
maxDistance = Math.max(distance, max);
}

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

import camp.nextstep.edu.missionutils.Console;
import java.util.Map;

public class View {

String inputCarName(){
System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,)기준으로 구분)");
return Console.readLine();
}

String inputNumberOfAttempts(){
System.out.println("시도할 회수는 몇회인가요?");
return Console.readLine();
}

void printResult(Map<String, Integer> result){

StringBuilder sb = new StringBuilder();
sb.append("\n실행 결과\n\n");

result.forEach((name, distance)-> sb.append(name).append(" : ")
.append("-".repeat(distance))
.append("\n"));
System.out.println(sb);
}

void printWinner(String winner){
System.out.print("최종 우승자 : ");
System.out.println(winner);
}
Comment on lines +18 to +32

Choose a reason for hiding this comment

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

출력도 따로 분리 했으면 좋았을거 같아용


}