From 6222e24cec51013cde5d390ccf320f87367f9845 Mon Sep 17 00:00:00 2001 From: oboil Date: Mon, 5 Aug 2024 13:36:08 +0900 Subject: [PATCH] =?UTF-8?q?docs(application):=20application=20=EC=9E=91?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 8 ++- src/main/java/Application.java | 118 +++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 src/main/java/Application.java diff --git a/README.md b/README.md index 491aece1..d8a54ce1 100644 --- a/README.md +++ b/README.md @@ -1 +1,7 @@ -# java-racingcar-precourse \ No newline at end of file +# java-racingcar-precourse + +**구현할 기능** +1. 자동차 이름 입력 +2. 난수에 따른 자동차 진행 +3. 자동차들 진행 출력 +4. 자동차들 진행 비교(우승자) \ No newline at end of file diff --git a/src/main/java/Application.java b/src/main/java/Application.java new file mode 100644 index 00000000..6ece6523 --- /dev/null +++ b/src/main/java/Application.java @@ -0,0 +1,118 @@ +import java.util.Scanner; +import java.util.ArrayList; +import java.util.Random; + +public class Application { + static String[] names; + static ArrayList cars = new ArrayList<>(); + static Scanner sc = new Scanner(System.in); + + public static void main(String[] args) { + + boolean inputEx = false; + + while (!inputEx) { + System.out.println("경주할 자동차 이름을 입력하세요.(이름은 쉽표(,) 기준으로 구분)"); + try { + inputName(); + inputEx = true; + } catch (IllegalArgumentException e) { + System.out.println("[ERROR] " + e.getMessage()); + } + + } + + System.out.println("시도할 횟수는 몇 회인가요?"); + int play = sc.nextInt(); + + System.out.println("실행 결과"); + printRace(play); + + winner(); + + } + + /* 자동차 이름 입력 */ + public static void inputName(){ + + String input = sc.nextLine(); + names = input.split(","); + + for (int i = 0; i 5) + throw new IllegalArgumentException("자동차 이름은 5글자 이하입니다."); + cars.add(new Car(names[i])); + } + + } + + /* 난수로 자동차 진행 */ + public static void step(){ + Random rand = new Random(); + for (Car car : cars){ + int go = rand.nextInt(10); + if ( go >= 4 ){ + car.go++; + } + } + } + + /* 자동차 진행 출력 */ + public static void printRace(int play){ + for (int i = 0; i < play; i++) { + step(); + printStep(); + } + } + public static void printStep(){ + for (Car car : cars){ + System.out.printf(car.name + " : " ); + printGo(car); + } + System.out.println(); + } + public static void printGo(Car c){ + for (int i=0; i winners = new ArrayList<>(); + + int maxGo = 0; + /* maxGo 정의 */ + for (Car car : cars){ + if (car.go > maxGo){ + maxGo = car.go; + } + } + + /* maxGo와 비교해 winner에 넣음 */ + for (Car car : cars){ + if (car.go == maxGo){ + winners.add(car); + } + } + + System.out.printf("최종 우승자 : "); + for (int i=0; i 0){ + System.out.printf(", "); + } + System.out.printf(winners.get(i).name); + } + } + +} + +class Car { + String name; + int go = 0; + + Car(String name){ + this.name = name; + } +} \ No newline at end of file