[김영한_자바입문][7. 훈련] While_if / switch구문, break / continue (p.23)
1. (while) if-break, switch-break의 쓰임은 다르다.
2. while내 switch-break를 사용할 때, 빠져나가려면 'return / exit'를 사용해라
3. if / else if / else 구문에서 원하는 흐름이 구현되었다면 continue를 사용할 필요 없다.
[p.23 / While_if 사용] break : while 구문에서 주로 사용되며, 실행 후 빠져나가는 역할
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.println("1.상품입력 | 2.결제 | 3. 프로그램 종료");
int option = scanner.nextInt();
if (option == 1) {
scanner.nextLine();
System.out.print("상품명을 입력하세요 : ");
String productName = scanner.nextLine();
System.out.print("상품의 가격을 입력하세요 : ");
int productPrice = scanner.nextInt();
System.out.print("구매 수량을 입력하세요 : ");
int quantity = scanner.nextInt();
sum += (productPrice * quantity);
System.out.println("상품명 : " + productName + ", 가격 : " + productPrice + ", 수량 : " + quantity + ", 합계 : " + (productPrice * quantity));
} else if (option == 2) {
System.out.println("총 비용 : " + sum);
} else if (option == 3) {
System.out.println("프로그램을 종료합니다.");
break;
} else {
System.out.println("올바른 옵션을 선택해주세요.");
}
}
}
* if 문은 조건에 따라 코드 블록을 실행하거나 실행하지 않는다.
* break 문은 주로 반복문에서 사용되며, 해당 반복문을 종료하는 역할을 합니다.
* 단순 if 문 안에서 break를 사용하는 것은 일반적이지 않다.
따라서 return 등의 키워드를 사용해 함수를 종료하거나, 코드 흐름을 다른 방향으로 바꾸는 데 사용된다.
[p.23 / While_switch 사용] : break는 case를 실행하고, 빠져나간다 (다음 case로 이동x)
1) switch에 return 추가
while (true) {
System.out.println("1.상품입력 | 2.결제 | 3. 프로그램 종료");
int option = scanner.nextInt();
switch (option) {
case 1:
scanner.nextLine();
System.out.print("상품명을 입력하세요 : ");
String productName = scanner.nextLine();
System.out.print("상품의 가격을 입력하세요 : ");
int productPrice = scanner.nextInt();
System.out.print("구매 수량을 입력하세요 : ");
int quantity = scanner.nextInt();
sum += (productPrice * quantity);
System.out.println("상품명 : " + productName + ", 가격 : " + productPrice + ", 수량 : " + quantity + ", 합계 : " + (productPrice * quantity));
break;
case 2:
System.out.println("총 비용 : " + sum);
break;
case 3:
System.out.println("프로그램을 종료합니다.");
return;
default:
System.out.println("올바른 옵션을 선택해주세요.");
}
}
}
2) if 구문 추가
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
while (true) {
System.out.println("1.상품입력 | 2.결제 | 3. 프로그램 종료");
int option = scanner.nextInt();
switch (option) {
case 1:
scanner.nextLine();
System.out.print("상품명을 입력하세요 : ");
String productName = scanner.nextLine();
System.out.print("상품의 가격을 입력하세요 : ");
int productPrice = scanner.nextInt();
System.out.print("구매 수량을 입력하세요 : ");
int quantity = scanner.nextInt();
sum += (productPrice * quantity);
System.out.println("상품명 : " + productName + ", 가격 : " + productPrice + ", 수량 : " + quantity + ", 합계 : " + (productPrice * quantity));
break;
case 2:
System.out.println("총 비용 : " + sum);
break;
case 3:
System.out.println("프로그램을 종료합니다.");
break;
default:
System.out.println("올바른 옵션을 선택해주세요.");
}
if (option == 3) {
break;
}
}
}
* switch 문은 여러 가지 경우에 따라 코드 블록을 실행하는데 사용된다.
* break 문은 switch 문에서 특정 case를 실행한 후, 다음 case로 이동하지 않도록 하는 역할을 한다.
* switch 문 전체를 빠져나가려면 break 대신 return이나 exit 등을 사용해야 합니다.
== 추가 확인 ==
[상기 코드 while문 발췌, 일부 제거]
while (true) {
System.out.println("1.상품입력 | 2.결제 | 3. 프로그램 종료");
int option = scanner.nextInt();
if (option == 1) {
scanner.nextLine();
System.out.print("상품명을 입력하세요 : ");
String productName = scanner.nextLine();
System.out.println("상품명 : " + productName);
} else if (option == 2) {
System.out.println("총 비용 : " + sum);
} else if (option == 3) {
System.out.println("프로그램을 종료합니다.");
break;
} else {
System.out.println("올바른 옵션을 선택해주세요.");
}
}
`else if (option == 3)`의 조건이 충족되면 `break`를 사용하여 빠져나가게 된다.
따라서 추가적으로 `else if`, 'else' 블록은 실행되지 않기 때문에 `continue`를 사용하지 않아도 된다.
즉 이후의 코드는 실행되지 않고 반복문으로 돌아가게 된다.
따라서, `continue`를 명시적으로 사용하지 않아도 원하는 흐름이 구현되었다면, 추가로 사용할 필요가 없다.
코드를 더 간결하고 이해하기 쉽게 작성하는 것이 중요하다.
▶ if / switch 접근
https://zoooom-in.tistory.com/35
[김영한_자바입문][4. 함수] if / switch 사용 이해하기(p.11-12)
요약하면, if-else 문은 다양한 조건을 처리하는 데 유연하고, switch 문은 옵션 출력 처럼 변수의 값에 따라 여러 경우 중 하나를 선택하는 경우 효과적이고, switch 표현식은 특히 값 할당과 관련된
zoooom-in.tistory.com
▶ break / continue 접근
https://zoooom-in.tistory.com/38
[김영한_자바입문][5. 반복문] break / continue 접근 (p.14-15)
break는 반복문을 완전히 종료하고 반복문 밖으로 나가며, continue는 현재 반복을 중단하고 반복문의 처음으로 돌아간다. 또한, 흔히 while 문에서 특정 조건(If구문)을 만족할 때 반복을 종료/재실행
zoooom-in.tistory.com
▶ While_단독 if 사용 / else 사용 로직 접근
https://zoooom-in.tistory.com/39
[김영한_자바입문][7. 훈련] 단독 if문 사용 / else 사용 로직 접근 (p.9)
입력 값이 무한 반복에 제한을 걸 상황은 'while'과 'if - break'를 사용해 코드 확인을 최소화하고 단순 제한이 있는 상황은 'if'와 'else'로 나누어 코드 확인을 최소화한다. [if / break 구분] 제한이 없
zoooom-in.tistory.com