지금까지 배운 1~4단원의 모든 개념(기본형과 참조형, 반복과 합 모으기, 클래스 설계도와 생성자 this, private 캡슐화, 객체 배열)을 하나로 엮어 플로우 카페 주문 영수증 프로그램을 완성해 봅시다.
막막하게 백지에서 시작하지 않고, 세 단계의 하위 목표(subgoals)와 변수 역할 이름표를 이정표 삼아 한 조각씩 조립합니다.
1세 단계 하위 목표와 변수 역할 이름표
| 하위 목표 | 변수 역할 이름표 | 하는 일 |
|---|---|---|
| 1. 항목 클래스 세우기 | 잠긴 상태 칸 (private price, qty) | 생성자로 값을 채우고 subtotal()로 단가 × 수량을 return합니다. |
| 2. 배열 순회하며 모으기 | 따라가는 칸 (OrderItem it) · 모으는 칸 (int total = 0) | OrderItem[] 배열을 돌며 total += it.subtotal()로 누적합니다. |
| 3. 할인과 영수증 찍기 | 결과 출력 | 총액이나 할인 적용 금액을 화면에 출력합니다. |
1단계: 완성된 주문서 코드 읽기와 return 대 println
먼저 하위 목표 1~3이 모두 채워진 완성 코드를 실행해 봅시다.
// [하위 목표 1] 항목 클래스 세우기
class OrderItem {
private int price;
private int qty;
OrderItem(int p, int q) {
this.price = p;
this.qty = q;
}
int subtotal() {
return this.price * qty;
}
}앞 코드에 이어 씁니다.
public class Main {
public static void main(
String[] args) {
OrderItem[] items = {
new OrderItem(4000, 2),
new OrderItem(4500, 1),
new OrderItem(2000, 1)};
int total = 0;
for (OrderItem it : items) {
total += it.subtotal();
}
System.out.println(
total + "원");
}
}14500원- 세 주문 항목(
커피 4000×2,라테 4500×1,쿠키 2000×1)의 소계가 모여14500원이 출력됩니다. subtotal()은 계산한 소계를return으로 돌려주기만 하고, 화면에 찍는 일은main마지막의println한 번이 맡습니다.
2단계별 빈칸 채우기 연습
2단계: 소계 메서드와 누적 한 줄 채우기
아래 코드에서 (가)와 (나) 자리(…)에 들어갈 알맞은 코드를 먼저 머릿속으로 떠올린 뒤 펼쳐서 답과 실행 결과를 확인해 보세요.
class OrderItem {
private int price;
private int qty;
OrderItem(int p, int q) {
this.price = p;
this.qty = q;
}
int subtotal() {
// (가) 단가 * 수량 돌려주기
return …;
}
}public class Main {
public static void main(
String[] args) {
OrderItem[] items = {
new OrderItem(4000, 2),
new OrderItem(4500, 1)};
int total = 0;
for (OrderItem it : items) {
// (나) 모으는 칸에 소계 더하기
…;
}
System.out.println(total);
}
}(가) · (나) 답과 실행 결과
(가)는 this.price * qty, (나)는 total += it.subtotal();입니다.
class OrderItem {
private int price;
private int qty;
OrderItem(int p, int q) {
this.price = p;
this.qty = q;
}
int subtotal() {
return this.price * qty;
}
}
public class Main {앞 코드에 이어 씁니다.
public static void main(
String[] args) {
OrderItem[] items = {
new OrderItem(4000, 2),
new OrderItem(4500, 1)
};
int total = 0;
for (OrderItem it :
items) {
total += it.subtotal();
}
System.out.println(
total);
}
}125003단계: 10,000원 이상 주문 시 1,000원 할인 영수증 완성하기
이번에는 하위 목표 3에 "total이 10000 이상이면 1000원을 뺀다"는 조건을 덧붙여 봅시다.
class OrderItem {
private int price;
private int qty;
OrderItem(int p, int q) {
this.price = p;
this.qty = q;
}
int subtotal() {
return this.price * qty;
}
}앞 코드에 이어 씁니다.
public class Main {
public static void main(
String[] args) {
OrderItem[] items = {
new OrderItem(4000, 2),
new OrderItem(4500, 1)};
int total = 0;
for (OrderItem it : items) {
total += it.subtotal();
}
if (total >= 10000) {
total -= 1000; }
System.out.println(total);
}
}115004단계: 스스로 짜고 자가 채점하기
내 컴퓨터의 Main.java에서 위 3단계 코드를 안 보고 직접 작성한 뒤, 아래 세 가지 기준으로 스스로 점검해 보세요.
- 시험 입력 2쌍 대조:
4000×2와4500×1두 항목 → 할인 전12500, 할인 후11500이 나오는가?2000×3한 항목 →10000미만이므로 할인 없이6000이 나오는가?
- 3줄 체크리스트:
-
OrderItem의 필드에private을 붙이고 생성자에서this.필드 = 매개변수;로 채웠는가? -
int subtotal()이println대신return으로 값을 돌려주는가? -
int total = 0;을for반복문 바깥 위쪽에 선언했는가?
-
- 흔한 실수 대조:
- 결과가
0이 나온다면 생성자 안에서this.를 빼먹어 자기 대입(price = price;)을 하지 않았는지 확인하세요.
- 결과가
자주 틀리는 곳
틀린 생각: subtotal()이 소계를 println으로 찍기만 해도 그 값이 total에 더해진다.
void 메서드는 화면에 글자를 내보낼 뿐, 부른 자리에는 아무 값도 남기지 않습니다. 그래서 total +=의 오른쪽에 더할 값이 없어 컴파일러가 막습니다.
class OrderItem {
private int price, qty;
void subtotal() {
System.out.println(
price * qty);
}
}
public class Main {
public static void main(
String[] args) {
var it = new OrderItem();
int total = 0;
total += it.subtotal();
}
}Main.java:13: error: bad operand types for binary operator '+' total += it.subtotal(); ^ first type: int second type: void1 errorfirst type: 줄은 += 왼쪽 total의 타입(int)이고, second type: 줄은 오른쪽 it.subtotal()의 타입(void)입니다. +=도 +로 더하는 계산이라 메시지에는 '+'가 찍힙니다.
맞는 규칙: 값을 돌려주는 return과 화면에 찍는 println은 서로 다른 일입니다. 그래서 subtotal()은 소계를 return하게 두고, 찍는 일은 다 모은 뒤 main에서 한 번만 합니다(규칙 6).
틀린 생각: 할인 if를 반복문 안에 넣어도 할인은 한 번만 빠진다.
반복문 안의 줄은 항목마다 다시 돕니다. 1절 세 항목의 소계만 배열에 담아, 할인 if를 반복문 안에 넣어 봅시다.
public class Main {
public static void main(
String[] args) {
int[] subs =
{8000, 4500, 2000};
int total = 0;
for (int s : subs) {
total += s;
if (total >= 10000) {
total -= 1000; }
}
System.out.println(total);
}
}12500합이 12500이 된 때와 13500이 된 때 두 번 빠져 12500이 찍힙니다. 다 모은 14500에서 한 번만 빼면 13500입니다.
맞는 규칙: 모으는 칸 total은 반복문이 다 돈 뒤에야 합계가 되므로, 할인은 그 뒤에 한 번만 겁니다. 그래서 할인 if는 3단계처럼 for를 닫은 다음 줄에 둡니다.
확인 문제
1. subtotal() 반환 타입과 누적
total += it.subtotal(); 줄이 컴파일 오류 없이 동작하기 위한 subtotal 메서드 선언으로 올바른 것은 무엇인가요?
- ①
int subtotal() { System.out.println(this.price * this.qty); } - ②
void subtotal() { System.out.println(this.price * this.qty); } - ③
int subtotal() { return this.price * this.qty; }
정답과 해설
정답: ③번 (int 반환 타입과 return 문 사용)
- ①: 반환 타입을
int로 적어 놓고return문을 적지 않으면missing return statement컴파일 오류가 납니다. - ②: 반환 타입이
void이면 돌려주는 값이 없어total += ...에 쓸 수 없습니다. - ③ (정답): 호출한 쪽의
total += ...식에 계산된 정수를 넘겨주어야 하므로 반환 타입을int로 적고return문으로 값을 돌려주어야 합니다.
2. 모으는 칸 선언 위치와 수량 변경 추적
다음 코드의 출력 결과로 알맞은 것은 무엇인가요?
class OrderItem {
private int price;
private int qty;
OrderItem(int p, int q) {
this.price = p;
this.qty = q;
}
void addOne() { this.qty++; }
int subtotal() {
return this.price * qty;
}
}앞 코드에 이어 씁니다.
public class Main {
public static void main(
String[] args) {
var a =
new OrderItem(4000, 1);
var b =
new OrderItem(2000, 2);
a.addOne();
System.out.println(
a.subtotal()
+ b.subtotal());
}
}- ①
10000 - ②
12000 - ③
8000
정답과 해설
정답: ② 12000
12000- ①:
8000 + 4000 = 12000입니다. - ② (정답):
a.addOne()을 호출해a의 수량(qty)이1에서2로 늘어났습니다. 따라서a.subtotal()은4000 * 2 = 8000,b.subtotal()은2000 * 2 = 4000이 되어 합계12000이 출력됩니다. - ③:
a.addOne()이a의 수량을2로 올렸으므로a.subtotal()은4000이 아니라8000입니다.
3. 영화관 예매 내역 총액 계산하기
영화관 예매 건(Booking) 배열을 순회해 총 결제 금액을 구하는 코드입니다. 출력 결과는 무엇인가요?
class Booking {
private int fee;
private int seats;
Booking(int f, int s) {
this.fee = f;
this.seats = s;
}
int amount() {
return this.fee * seats;
}
}앞 코드에 이어 씁니다.
public class Main {
public static void main(
String[] args) {
Booking[] list = {
new Booking(12000, 2),
new Booking(9000, 1)};
int sum = 0;
for (Booking b : list) {
sum += b.amount();
}
System.out.println(sum);
}
}- ①
33000 - ②
21000 - ③
24000
정답과 해설
정답: ① 33000
33000- ① (정답): 첫 예매 건의
amount()는12000 * 2 = 24000, 두 번째 예매 건의amount()는9000 * 1 = 9000이며, 두 값을sum에 누적하면24000 + 9000 = 33000이 출력됩니다. - ②: 좌석 수(
seats)를 곱하지 않고 단가만 더하면21000이 됩니다. - ③: 첫 번째 예매 건의 금액만 계산한 값입니다.
