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
11 changes: 11 additions & 0 deletions '
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
commit 9ee2c3533fc9409283a740bc00936d7c0b52e9b4 (HEAD -> szoon2426)
Author: szoon2426 <s.zoon2426@gmail.com>
Date: Fri Feb 14 23:19:54 2025 +0900

기본 기능 추가

commit b9d9f2b0e3858ba8e98b53882eb49e7ae8cdd248 (origin/main, origin/HEAD, main)
Author: moongua404 <hogun.soongit@gmail.com>
Date: Mon Jan 6 01:19:25 2025 +0900

feat: project-setup
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
# java-racingcar-precourse
## 추가할 목록
- 게임에 참여할 참가자는 모두 각자 자동차가 있고 이름이 있다. 이름은 ,로 구분한다. 레이싱 후 결과를 알려주고 승자를 알린다. 승자가 여러명 일 경우 ,로 구분한다. 레이싱을 여러번 할 수 있도록 시도할 횟수를 입력받는다.
- 사용자가 잘못된 값을 입력할 경우 IllegalArgumentException을 발생시킨 후 애플리케이션은 종료되어야 한다.
74 changes: 73 additions & 1 deletion src/main/java/racingcar/Application.java
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

거의 대부분 static을 쓰셨는데 그 이유가 있으실까용?

Original file line number Diff line number Diff line change
@@ -1,7 +1,79 @@
package racingcar;

import camp.nextstep.edu.missionutils.Randoms;
import camp.nextstep.edu.missionutils.Console;
import java.util.Vector;
import java.util.stream.Collectors;
import java.util.regex.Pattern;

public class Application {
static Vector<Player> listOfPlayers = new Vector<>();
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Vector를 java에서 쓰지않는이유

vector대신 arraylist를 활용하는 것은 어떨까용?? 불필요한 동기화처리도 줄이고 성능적으로도 더 적절해요!


// 레이싱 돌려잇
static void game(){
for(int i = 0; i<listOfPlayers.size(); i++){
if(Randoms.pickNumberInRange(0,9) >=4){
listOfPlayers.get(i).addDistance();
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

listofPlayers에 대해서 for문을 돌리시는 것 같은데, 만약 내부의 인스턴스를 사용하실거면 .forEach()를 찾아보고 그걸 쓰는 방향으로 고치고 써보시면 더 좋을 것 같습니다!

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

동의합니다

}
}

// 게임 결과
static String getGameResult(int player){
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

player을 매개변수로 받기보다는 player객체 자체를 받아서 출력하는 방향이 더 좋을 듯 해용

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

동의합니다~~ 이러면 내부 로직의 함수 호출을 한번으로 줄일 수 있을 듯 싶습니다~~

return (listOfPlayers.get(player).getName() + " : "
+ listOfPlayers.get(player).printDistance());
}

// 승자의 거리
static int distanceOfWinner(){
int answer = 0;
for(int i = 0; i<listOfPlayers.size();i++){
if(listOfPlayers.get(i).getDistance() > answer){
answer = listOfPlayers.get(i).getDistance();
}
}
return answer;
}

// 승자 출력
static String printWinner(){
int value = distanceOfWinner();
Vector<String> listOfWinners = new Vector<>();
for(Player player : listOfPlayers){
if(player.getDistance() == value){
listOfWinners.add(player.getName());
}
}
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 문도 가능하다면 stream을 이용하면 코드가 더 간략해지고 이해하기 쉬울 것 같아요! 대신 한 번 열린 stream은 재사용이 불가하니 한 번 해당 내용에 대해 알아보시는 것도 좋을 것 같네요,

return listOfWinners.stream().collect(Collectors.joining(", "));
}

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

// input
System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)");
String names = Console.readLine();
System.out.println("시도할 횟수는 몇회인가요?");
int times = Integer.parseInt(Console.readLine());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

만약 이렇게 하시면 .parseInt부분에서 미션 요구조건의 예외 타입과 다른 예외가 나올 수도 있을 것 같습니다! 잘못된 입력에 따라 IllegalExpression이었나..아무튼 이 에러를 throw하게 고치시면 더 좋을 것 같습니다~~

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

동의합니당

// 입력받은 이름들을 player 리스트에 담아줌
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(String name : names.split(",")){
if(name.length()>5){ // 예외처리
throw new IllegalArgumentException();
}
Player player = new Player((name));
listOfPlayers.add(player);
}

// output
System.out.println("\n실행 결과");
for(int i = 0; i<times; i++){
game();
for(int j = 0; j<listOfPlayers.size(); j++){
System.out.println(getGameResult(j));;
}
System.out.println();
};
System.out.printf("최종 우승자 : " + printWinner());
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

단순 문자열 출력이라 포맷팅이 필요하지않아보이는데 printf를 쓰신 이유가 있을까용??

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

어,, 잘 모르고 그냥 사용했는데 printf의 의미를 더 알아보고 사용해보도록 하겠습니다!!!

}
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

주석으로 설명을 붙인 메서드들을 다른 폴더들에 분리해서 작성하고 정리하는 게 프로젝트 파일을 보는데 더 편할 것 같아요! 한 번 시간 나실 때 MVC 패턴에 대해 검색해 보세요. 저도 처음 코딩할 땐 굳이? 싶었지만 직접 해보니 코드 작성이 더 깔끔해지는 것 같아요!

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

public class Player {
private String name;
private int distance;
Player(){
this.name = "";
this.distance = 0;
}
Player(String name){
this.name = name;
this.distance = 0;
}
Comment on lines +6 to +13
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
Player(){
this.name = "";
this.distance = 0;
}
Player(String name){
this.name = name;
this.distance = 0;
}
public class Player {
private static final int DEFAULT_DISTANCE = 0;
private String name;
private int distance;
Player() {
this("", DEFAULT_DISTANCE); // 기본 생성자에서 다른 생성자 호출
}
Player(String name) {
this(name, DEFAULT_DISTANCE); // 중복 제거
}
Player(String name, int distance) {
this.name = name;
this.distance = distance;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

이런식으로 바꾸면 중복코드도 제거되고 가독성도 좋아질 것 같아용
기존 코드는 모든 생성자에서 중복으로 distance를 설정해야해서 기본값이 바뀔 경우 모든 생성자를 다 수정해야하지만,
수정 코드는 기본값을 한 곳에서 통제가능해서 유지보수성이 좋아질 듯 해용

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

확실히 저렇게 수정하는게 실수도 줄이고 읽고 이해하기 편해 보이네요. 저도 한 수 배우고 갑니다..!

void addDistance(){
distance++;
}
String getName(){
return name;
}
String printDistance(){
String answer = "";
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stirng은 변경 불가능한 문자열을 생성하지만 StringBuilder는 변경 가능한 문자열을 만들어 주기 때문에, String을 합치는 작업 시 하나의 대안이 될 수 있다. (링크한 블로그에서 따온 문구)
StringBuilder사용법

answer을 ""로 선언하고 answer += "-"; 을 반복하는 방식은 문자열이 계속 생성되기때문에 성능저하가 일어날 수 있대용
StringBuilder를 사용하여 최적화를 해보는건 어떨까용?

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(int i = 0; i<distance;i++){
answer += "-";
}
return answer;
}
int getDistance(){
return distance;
}
}