-
Notifications
You must be signed in to change notification settings - Fork 7
[8주차] ysy #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
[8주차] ysy #53
Changes from 15 commits
2da042e
6555d2a
bbd117d
ea017bf
0df622d
e834702
2cac2e8
c05f489
a0e7017
79e22bd
24fef7c
8c84718
201fda2
84e4e2c
ac1279e
6564893
433cff1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
|
|
||
| # Created by .ignore support plugin (hsz.mobi) | ||
| ### Java template | ||
| # Compiled class file | ||
| *.class | ||
|
|
||
| # Log file | ||
| *.log | ||
|
|
||
| # BlueJ files | ||
| *.ctxt | ||
|
|
||
| # Mobile Tools for Java (J2ME) | ||
| .mtj.tmp/ | ||
|
|
||
| # Package Files # | ||
| *.jar | ||
| *.war | ||
| *.nar | ||
| *.ear | ||
| *.zip | ||
| *.tar.gz | ||
| *.rar | ||
|
|
||
| # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml | ||
| hs_err_pid* | ||
|
|
||
| .DS_Store | ||
| .gradle | ||
| /build/ | ||
| !gradle/wrapper/gradle-wrapper.jar | ||
| /out/ | ||
| /target/ | ||
|
|
||
| ### STS ### | ||
| .apt_generated | ||
| .classpath | ||
| .factorypath | ||
| .project | ||
| .settings | ||
| .springBeans | ||
| bin/ | ||
|
|
||
| ### IntelliJ IDEA ### | ||
| .idea | ||
| *.iws | ||
| *.iml | ||
| *.ipr |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| import utils.GameUtils; | ||
|
|
||
| public class Application { | ||
| public static void main(String[] args) { | ||
| GameUtils gameUtils = new GameUtils(); | ||
| gameUtils.run(); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| package inpututils; | ||
|
|
||
| import java.util.Scanner; | ||
|
|
||
| public class InputView { | ||
| private static final Scanner SCANNER = new Scanner(System.in); | ||
|
|
||
| public static String getCarName() { | ||
| System.out.print("경주 할 자동차 이름 : "); | ||
| return SCANNER.nextLine(); | ||
| } | ||
|
|
||
| public static int getTryNumber() { | ||
| System.out.print("시도할 횟수 : "); | ||
| try { | ||
| return SCANNER.nextInt(); | ||
| } catch (NumberFormatException e) { | ||
| throw new NumberFormatException("[ERROR] 시도 횟수는 숫자여야 한다."); | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| package outpututils; | ||
|
|
||
| import java.util.ArrayList; | ||
|
|
||
| public class OutputView { | ||
| private OutputView() { | ||
| } | ||
|
|
||
| public static void printCarName(String name) { | ||
| System.out.print(name + " : "); | ||
| } | ||
|
|
||
| public static void printMove() { | ||
| System.out.print("-"); | ||
| } | ||
|
|
||
| public static void printWinner(ArrayList<String> winner) { | ||
| //TODO:마지막에 , 나오지 않도록 수정 필요 | ||
| winner.stream() | ||
| .forEach(w -> System.out.print(w + ",")); | ||
| } | ||
| } | ||
|
Comment on lines
+17
to
+22
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 마지막에 ,이 나오지 않도록 수정 필요 |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package racingcar; | ||
|
|
||
| import utils.GameUtils; | ||
|
|
||
| public class Car { | ||
| private final String name; | ||
| private int position = 0; | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 생성시점에 초기화 해 주는 방법도 좋은 방법일 것 같습니다
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 프로그래밍 요구사항-Car객체에서 해당 부분이 고정인 것 같아 그대로썼는데, 생성시점에 초기화 해주는 방법이라는 것이 어떤 것인지 잘 이해가 가지 않습니다! |
||
|
|
||
| public Car(String name) { | ||
| this.name = name; | ||
| } | ||
|
|
||
| public String getName(){ | ||
| return name; | ||
| } | ||
|
|
||
| public int plusPosition(){ | ||
| return position++; | ||
| } | ||
|
|
||
| public int getPosition() { | ||
| return position; | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| package racingcar; | ||
|
|
||
| import outpututils.OutputView; | ||
| import utils.RandomUtils; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| public class Cars { | ||
| private static List<Car> carList; | ||
|
|
||
| private static final int START_NUMBER = 0; | ||
| private static final int END_NUMBER = 9; | ||
|
|
||
| private static final int BOUNDARY_NUMBER = 4; | ||
|
|
||
| private static ArrayList<String> winner; | ||
|
|
||
| public Cars(List<Car> carList) { | ||
| this.carList = carList; | ||
| } | ||
|
|
||
| public static boolean isMove(int randomNumber) { | ||
| if (randomNumber >= BOUNDARY_NUMBER) { | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| public static void playGame() { | ||
| for (int j = 0; j < carList.size(); j++) { | ||
| OutputView.printCarName(carList.get(j).getName()); | ||
|
|
||
| if (isMove(RandomUtils.nextInt(START_NUMBER, END_NUMBER))) { | ||
| carList.get(j).plusPosition(); | ||
| } | ||
| for (int k = 0; k < carList.get(j).getPosition(); k++) { | ||
| OutputView.printMove(); | ||
| } | ||
| System.out.println(); | ||
| } | ||
| } | ||
|
Comment on lines
+29
to
+41
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. code indent 수정 필요 |
||
|
|
||
| public static int getMax() { | ||
| int max = carList.stream() | ||
| .mapToInt(Car::getPosition) | ||
| .max() | ||
| .getAsInt(); | ||
| return max; | ||
| } | ||
|
|
||
| public static void setWinnerList(int max) { | ||
| winner = new ArrayList<String>(); | ||
| for (int i = 0; i < carList.size(); i++) { | ||
| if (max == carList.get(i).getPosition()) { | ||
| winner.add(carList.get(i).getName()); | ||
| } | ||
| } | ||
| } | ||
|
dustndus8 marked this conversation as resolved.
Outdated
|
||
| public static ArrayList<String> getWinnerList() { | ||
| return winner; | ||
| } | ||
|
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package utils; | ||
|
|
||
| import inpututils.InputView; | ||
| import outpututils.OutputView; | ||
| import racingcar.Car; | ||
| import racingcar.Cars; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class GameUtils { | ||
|
dustndus8 marked this conversation as resolved.
|
||
|
|
||
| public static List<Car> makeCarList(String[] splitResult) { | ||
| return Arrays.stream(splitResult) | ||
| .map(Car::new) | ||
| .collect(Collectors.toList()); | ||
| } | ||
|
|
||
| public static void run() { | ||
| String inputName = InputView.getCarName(); | ||
| int inputCount = InputView.getTryNumber(); | ||
| String[] splitResult = SplitString.splitString(inputName); | ||
|
|
||
| Cars cars = new Cars(makeCarList(splitResult)); | ||
|
|
||
| for (int i = 0; i < inputCount; i++) { | ||
| Cars.playGame(); | ||
| System.out.println(); | ||
| } | ||
|
|
||
| Cars.setWinnerList(Cars.getMax()); | ||
| OutputView.printWinner(Cars.getWinnerList()); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| package utils; | ||
|
|
||
| import java.util.Random; | ||
|
|
||
| public class RandomUtils { | ||
| private static final Random RANDOM = new Random(); | ||
|
|
||
| private RandomUtils() { | ||
| } | ||
|
|
||
| public static int nextInt(final int startInclusive, final int endInclusive) { | ||
| if (startInclusive > endInclusive) { | ||
| throw new IllegalArgumentException(); | ||
| } | ||
| if (startInclusive < 0) { | ||
| throw new IllegalArgumentException(); | ||
| } | ||
|
|
||
| if (startInclusive == endInclusive) { | ||
| return startInclusive; | ||
| } | ||
| return RANDOM.nextInt(endInclusive - startInclusive + 1) + startInclusive; | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package utils; | ||
|
|
||
| public class SplitString { | ||
|
dustndus8 marked this conversation as resolved.
|
||
| private SplitString() { | ||
| } | ||
|
|
||
| public static String[] splitString(String input) { | ||
| return input.split(","); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,131 @@ | ||
| # 자바 스트림(Stream) 정리 | ||
|
|
||
| ## 스트림(Stream)이란? | ||
| > 자바 8부터 추가된 컬렉션의 저장 요소를 하나씩 참조해 람다식으로 처리할 수 있도록 해주는 반복자 | ||
| > Iterator과 비슷한 역할을 하지만 람다식을 이용해 코드가 좀 더 간결할 수 있다. | ||
|
|
||
| 1. 생성하기: 스트림 인스턴스 생성 | ||
| 2. 가공하기: 필터링 및 맵핑 등 원하는 결과를 만들어가는 과정 | ||
| 3. 결과 만들기: 최종적으로 결과를 만들어내는 작업 | ||
|
|
||
| ## 생성하기 | ||
|
|
||
| ### 배열 스트림 | ||
| Arrays.stream 메소드를 이용 | ||
| ``` | ||
| String[] strArr = new String[]{"김가나", "이다라", "박마바"}; | ||
| Stream<String> stream = Arrays.stream(strArr); | ||
| Stream<String> streamOfArrayPart = | ||
| Arrays.stream(strArr, 1, 3); // 1~2 요소 ["이다라", "박마바"] | ||
| ``` | ||
| ### 컬렉션 스트림 | ||
| 컬렉션 타입(Collection,List,Set) 은 stream 이용 | ||
| ``` | ||
| public interface Collection<E> extends Iterable<E> { | ||
| default Stream<E> stream() { | ||
| return StreamSupport.stream(spliterator(), false); | ||
| } | ||
| // ... | ||
| } | ||
| ``` | ||
| 다음과 같이 생성 | ||
| ``` | ||
| List<String> list = Arrays.asList("a", "b", "c"); | ||
| Stream<String> stream = list.stream(); | ||
| Stream<String> parallelStream = list.parallelStream(); // 병렬 처리 스트림 | ||
| ``` | ||
|
|
||
| ### Stream.builder() | ||
| 스트림에 직접 원하는 값을 넣을 수 있고, build 메소드로 스트림을 리턴 | ||
| ``` | ||
| Stream<String> builderStream = | ||
| Stream.<String>builder() | ||
| .add("AB").add("CC").add("JJ") | ||
| .build(); // [AB, CC, JJ] | ||
| ``` | ||
|
|
||
| ### Stream.generate() | ||
| Supplier<T>에 해당하는 람다로 값을 넣을 수 있다. Supplier<T>는 인자는 없고 리턴값만 있는 함수형 인터페이스 | ||
| ``` | ||
| public static<T> Stream<T> generate(Supplier<T> s) { ... } | ||
| ``` | ||
| 이때 생성되는 스트림은 크기가 정해져있지 않기 때문에 특정 사이즈로 크기 제한 해야한다. | ||
| ``` | ||
| Stream<String> generatedStream = | ||
| Stream.generate(() -> "gen").limit(5); // [el, el, el, el, el] | ||
| ``` | ||
|
|
||
| ## 가공하기 | ||
| 스트림을 리턴하기 때문에 여러 작업을 이어 붙여 작성 가능 | ||
| ``` | ||
| List<String> names = Arrays.asList("Eric", "Elena", "Java"); | ||
| ``` | ||
| 위의 리스트를 대상으로 예제 코드를 작성 | ||
|
|
||
| ### Filtering | ||
| ``` | ||
| Stream<T> filter(Predicate<? super T> predicate); | ||
| ``` | ||
| ``` | ||
| Stream<String> stream = | ||
| names.stream() | ||
| .filter(name -> name.contains("a")); | ||
| // [Elena, Java] | ||
| // 'a' 가 들어간 이름만 스트림 리턴됨 | ||
| ``` | ||
|
|
||
| ### Mapping | ||
| ``` | ||
| <R> Stream<R> map(Function<? super T, ? extends R> mapper); | ||
| ``` | ||
|
|
||
| ``` | ||
| Stream<String> stream = | ||
| names.stream() | ||
| .map(String::toUpperCase); | ||
| // [ERIC, ELENA, JAVA] | ||
| ``` | ||
| toUpperCase로 대문자로 변환된 값들이 담긴 스트림 리턴 | ||
|
|
||
| ``` | ||
| Stream<Integer> stream = | ||
| productList.stream() | ||
| .map(Product::getAmount); | ||
| // [23, 14, 13, 23, 13] | ||
| ``` | ||
| Product 개체의 수량을 꺼내올 수 있다 | ||
|
|
||
| ## 결과 만들기 | ||
| 가공한 스트림으로 내가 사용할 결과값을 만들어내는 단계이다. | ||
|
|
||
| ### Calculating | ||
| ``` | ||
| long count = IntStream.of(1, 3, 5, 7, 9).count(); | ||
| long sum = LongStream.of(1, 3, 5, 7, 9).sum(); | ||
| ``` | ||
| min(),max()와 같은 것도 가능 | ||
|
|
||
| ### Collecting | ||
| collect 메소드는 또 다른 종료 작업으로, Collector 타입의 인자를 받아 처리함 | ||
| ``` | ||
| List<Product> productList = | ||
| Arrays.asList(new Product(23, "potatoes"), | ||
| new Product(14, "orange"), | ||
| new Product(13, "lemon"), | ||
| new Product(23, "bread"), | ||
| new Product(13, "sugar")); | ||
| ``` | ||
| 다음 예제에는 이 Product 객체를 사용 | ||
|
|
||
| ### Collectors.toList() | ||
| 스트림에서 작업한 결과를 담은 리스트로 반환한다. | ||
| ``` | ||
| List<String> collectorCollection = | ||
| productList.stream() | ||
| .map(Product::getName) | ||
| .collect(Collectors.toList()); | ||
| // [potatoes, orange, lemon, bread, sugar] | ||
|
|
||
| ``` | ||
|
|
||
| [출처, 더 많은 내용 참고](https://futurecreator.github.io/2018/08/26/java-8-streams/) |
Uh oh!
There was an error while loading. Please reload this page.