김영한의 자바 입문 - 문제 ) 상품구매

하히호호·2024년 3월 28일
0

문제

실행결과

나는 switch문을 사용했다.
번호가 정확히 정해져 있기에 case로 나누면 가독성이 올라가기 때문이다.

풀이

while 안에 swicth문 풀이

완성 풀이

package scanner.ex;
//상품구매
import java.util.Scanner;

public class ScannerWhileEx4 {
    public static void main(String[] args) {
        boolean run = true;
        Scanner scanner = new Scanner(System.in);
        int total = 0;

        while (run) {
            System.out.println("1:상품입력, 2:결제, 3:프로그램 종료");
            int option = scanner.nextInt();
            scanner.nextLine();//\n값 버려주기

            switch (option) {
                case 1 -> {
                    System.out.print("상품명을 입력하세요: ");
                    String name = scanner.nextLine();
                    System.out.print("상품 가격을 입력하세요: ");
                    int price = scanner.nextInt();
                    System.out.print("상품 수량을 입력하세요: ");
                    int amount = scanner.nextInt();

                    total += price * amount;
                    System.out.println("상품명:"+name+" 가격:"+price+" 수량:"+amount+" 합계:"+price*amount);
                }
                case 2 -> {
                    System.out.println("총비용: " + total);
                    total = 0;
                }
                case 3 -> {
                    System.out.println("프로그램을 종료합니다.");
                    run = false;
                    //break;
                }default -> System.out.println("잘못 입력했습니다.");
            }
        }
    }
}

계속 풀리지 않는 문제가 발생했다. switch문은 break; 로 빠져나왔지만 while문을 빠져나오지 않는다는 점이다. break;가 안먹히는 상황이다.

while 문안에 switch문이 있을 경우, 발생하는 문제

사용자가 종료를 원할때까지 계속 돌아가야하기 때문에 while문으로 전체 코드를 감싸고 있다. switch문을 사용했는데, break;문이 안먹히더라...ㅎ
case문만 빠져나가고 while문은 계속됐다.

처음 시도한 문제의 코드

package scanner.ex;
//상품구매
import java.util.Scanner;

public class ScannerWhileEx4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = 0;

        while (true) {
            System.out.println("1:상품입력, 2:결제, 3:프로그램 종료");
            int option = scanner.nextInt();
            scanner.nextLine();//\n값 버려주기

            switch (option) {
                case 1 -> {
                    System.out.print("상품명을 입력하세요: ");
                    String name = scanner.nextLine();
                    System.out.print("상품 가격을 입력하세요: ");
                    int price = scanner.nextInt();
                    System.out.print("상품 수량을 입력하세요: ");
                    int amount = scanner.nextInt();

                    total += price * amount;
                    System.out.println("상품명:"+name+" 가격:"+price+" 수량:"+amount+" 합계:"+price*amount);
                }
                case 2 -> {
                    System.out.println("총비용: " + total);
                    total = 0;
                }
                case 3 -> {
                    System.out.println("프로그램을 종료합니다.");
                    break;
                }default -> System.out.println("잘못 입력했습니다.");
            }
        }
    }
}

(결과)
1:상품입력, 2:결제, 3:프로그램 종료
3
프로그램을 종료합니다.
1:상품입력, 2:결제, 3:프로그램 종료

이때 든 생각은 2가지였다.
1. 사용자 입력값을 전역으로 남기고 while문에 조건을 걸어야하는가?
2. switch문에서 사용자가 3을입력하면 while문을 false로 만드는 방법이없을까?

물론, 나는 아직 코린이라 저렇게 생각을 코드로 호로록 만들지는 못하지만 1번 방법은 김영한 선생님께서 의미없이 전역변수를 만들면 불필요한 메모리가 사용되고 계속 신경쓰면서 코드를 짜야하니, 필요한게 아니면 안만드는게 좋다고 하셨다.!

개인적으로도 2번 방법이 궁금했다. 이게 가능하다면 다음부터 써먹을 수 있지 않을까?하는 날먹..?느낌이라서 찾아보고 싶었다.

(구글링 구글링)

그렇다. 이미 들어온 switch문에서 while의 조건을 바꾸는건 쉽지 않다.
while에 영향을 미치기 위해서는 전역변수를 사용해야하는건 어쩔 수 없나보다!

정리 정리!
1. 전역에 boolean run = true; 라고 설정하고
2. while (run)으로 조건을 달아준다.
3. switch case 3에서 run = false;를 설정해준다.

if문 풀이

김영한 선생님은 if문으로 문제를 푸셨기에 나도 if문으로 문제를 풀어봤다.

package scanner.ex;
//상품구매
import java.util.Scanner;

public class ScannerWhileEx4 {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
        int total = 0;

        while (true) {
            System.out.println("1:상품입력, 2:결제, 3:프로그램 종료");
            int option = scanner.nextInt();
            scanner.nextLine();//\n값 버려주기

            if (option == 1) {
                System.out.print("상품명을 입력하세요: ");
                String name = scanner.nextLine();
                System.out.print("상품 가격을 입력하세요: ");
                int price = scanner.nextInt();
                System.out.print("상품 수량을 입력하세요: ");
                int amount = scanner.nextInt();

                total += price * amount;
                System.out.println("상품명:" + name + " 가격:" + price + " 수량:" + amount + " 합계:" + price * amount);
            } else if (option == 2) {
                System.out.println("총비용: " + total);
                total = 0;
            } else if (option == 3) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else {
                System.out.println("잘못 입력했습니다.");
            }
        }
    }
}
profile
읽히는 코드를 짜고싶습니다.

0개의 댓글