23.06.01
개인과제에 총 매출을 출력하는 메서드를 추가해 보자.
총 매출을 출력하는 메서드를 만들기 위해 기존의 개인 장바구니를 출력하는 메서드를 재활용하려고 했으나, 기존 메서드는 상품개수를 처음에 1개로 초기화 하는 문제가 있어 조금 수정했다.
public Cart(String menuName, int price) {
this.menuName = menuName;
this.price = price;
this.count = 1;
}
public Cart(String menuName, int price, int count) {
this.menuName = menuName;
this.price = price;
this.count = count;
}
public void addOrder(String menuName, int price) {
Cart plusCount = plusCount(menuName);
if (plusCount != null) {
plusCount.plusCount();
} else {
Cart cart = new Cart(menuName, price);
order.add(cart);
}
}
public void addOrder(String menuName, int price, int count) {
Cart plusCount = plusCount(menuName);
if (plusCount != null) {
plusCount.plusCount();
} else {
Cart cart = new Cart(menuName, price, count);
order.add(cart);
}
}
public void plusCount() {
count++;
}
public void plusCount(int count) {
this.count += count;
}
현재 장바구니를 초기화 하기 전에 안에 있는 내용을 전체 매출 내용에 추가하는 메서드를 만들었다.
public void total(Order order) {
for (Cart cart : this.order) {
String menuName = cart.getMenuName();
int price = cart.getPrice();
int count = cart.getCount();
order.addOrder(menuName, price, count);
}
}
위에서 참조할 변수와 추가할 변수를 반대로 설정해 제대로 저장되지 않는 오류가 발생했다.
참조를 제대로 설정해 아래와 같이 수정했다.
public void total(Order order) {
for (Cart cart : order.order) {
String menuName = cart.getMenuName();
int price = cart.getPrice();
int count = cart.getCount();
this.addOrder(menuName, price, count);
}
}
마지막으로 메인메뉴판에서 999을 입력하면 반복문을 탈출해 메인 쓰레드를 종료시키는 기능을 넣어 마무리했다.
완성 코드는 너무 길어 github 주소로 남긴다.
https://github.com/hjh3229/kiosk/tree/master/src/kioskMaking_2
GitHub - hjh3229/kiosk
Contribute to hjh3229/kiosk development by creating an account on GitHub.
github.com
개인과제를 끝마치고 이제 java 문법 5주차 숙제를 해보려고 한다.
첫 번째부터 큰 벽을 만난 기분... stream에 대해 배우긴 했다만 최대한 배운 걸 활용해
bookList.stream().filter((Book book) -> book.getCategory().equals("여행"))
.forEach(System.out::println(~~~));
위와 같이 만들었더니 알 수 없는 오류가 자꾸 발생한다. 스트림 메서드와 로직을 제대로 몰라서 결구 힌트를 봤는데 아예 모르던 방식으로 출력하는 것을 볼 수 있었다.
bookList.stream().filter((Book book) -> book.getCategory().equals("여행"))
.forEach(f -> System.out.println("카테고리가 여행인 책 제목 : " + f.getBookName()));
그래도 다음 힌트는 안보고 만드는 것을 목표로 재설정하고 가격이 16200원 이하인 책 제목 조회를 해결해보자.
가격이 가장 비싼 책 조회에서도 애를 먹었다.
forEach나 map 등 모두 안에서 조건문을 실행시키려 해도 (Book book) -> 을 통해 실행시킬려니 밖에 있는 변수를 사용할 수가 없어 난항을 겪었다. 그래서 힌트를 봤는데 이번에도 본적없는 메서드를 실행해서 푸는거였다.
double maxPrice = bookList.stream().mapToDouble(Book::getPrice)
.max().getAsDouble();
System.out.println("책 목록 중 가장 비싼 금액: " + maxPrice);
System.out.println();
IT 책 40% 할인도 힘들긴 했으나 어찌어찌 만들긴 했다.
List<Book> discountedBookList = bookList.stream().filter((Book book) -> book.getCategory().equals("IT"))
.map(book -> {
book.setPrice(book.getPrice() * 0.6);
return book;
}).collect(Collectors.toList());
for (Book book : discountedBookList) {
System.out.println("할인된 책 제목: " + book.getBookName());
System.out.println("할인된 책 가격: " + book.getPrice() + "\n");
}