Contents
접기
초기식
while (조건식) {
반복할 문장;
증감식;
}
1) ++i 의 위치마다 다른 i 의 시작값 차이
public class WhileTest1 {
public static void main(String[] args) {
int i = 0 ;
/*
while (i<10) {
++i; // 1부터 시작됨
System.out.println(i);
//++i; // 0부터 시작됨
}
System.out.println("끝");
*/
2) 증가후 비교 => 1부터 시작
while (++i<10) {
System.out.println(i);
}
System.out.println("끝");
3) 비교 후에 참인지 확인 후 증가
진입(참이기 때문에)
while (i++<10) {
System.out.println(i);
}
System.out.println("끝");
4) 1부터 10까지 홀수만 출력
1) 조건식 없이
i =1;
while (i<10) {
System.out.println(i);
i += 2;
}
System.out.println("끝");
2) (개인) 조건식 넣어서
i =0;
while (i<10) {
if (i %2 != 0) {
System.out.println(i);
++i;
}
++i;
}
System.out.println("끝");
5) 짝수만
* 반복문을 여러 개 겹쳐서 작성해도 break; 는 자신을 감싼 한개의 반복문만 빠져나간다
while(true) {
System.out.println(i);
i+=2;
if(i>10) break; // 자신을 감싼 한개의 반복문만 빠져나감
}
System.out.println("끝");
6) 무한 반복
while (i<10)
System.out.println(1);
7) ; - null statement
식이 누락된 식 문. 세미콜론으로 구성. 오류는 아님
언어의 구문에 문이 필요하지만 식 계산은 필요하지 않은 경우에 이 문이 유용하다.
문제
[Q] 두 개의 정수값을 입력받고, 연산 종류를 입력 받아 결과를 출력
* 휴먼 오류는 없는 걸로 가정
<실행 예시>
1. 덧셈
2. 뺄셈
3. 곱셈
4. 나눗셈
0. 종료
------------
선택 : 2
두개의 정수 입력: 10 20
결과 : -10
import java.util.Scanner;
public class Exam13 {
public static void main(String[] args) {
int x, y;
int menu;
double result = 0;
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("1. 덧셈");
System.out.println("2. 뺄셈");
System.out.println("3. 곱셈");
System.out.println("4. 나눗셈");
System.out.println("0. 종료");
System.out.println("------------");
System.out.print("선택: ");
menu = scanner.nextInt();
if (menu == 0) {
System.out.println("프로그램을 종료합니다.");
break;
} // early stopping
if (menu<1 || menu >4) {
System.out.println("## 메뉴를 다시 선택");
continue; // 아래쪽 명령문을 스킵
}
System.out.print("두 개의 정수 입력: ");
x = scanner.nextInt();
y = scanner.nextInt();
switch(menu) {
case 1 -> result = x + y;
case 2 -> result = x - y;
case 3 -> result = x * y;
case 4 -> result = x / (double)y;
}
System.out.println("결과: " + result);
}
}
}
코드 | 코드 |
switch(menu) { case 1 -> result = x + y; case 2 -> result = x - y; case 3 -> result = x * y; case 4 -> result = x / (double)y; } |
switch(menu) { case 1 : result = x + y; case 2 : result = x - y; case 3 : result = x * y; case 4 : result = x / (double)y; } |
왜 두 개의 값이 다르게 나올까? ==> break를 안쓰면 모든 case를 사용하기 때문이다. |
break | continue |
switch 문이나 반복문에서 빠져나오고자 할 때 사용 하나의 블록 {} 만 빠져 나올 수 있다. |
반복문과 함께 사용 반복문 내에서 continu문을 만나면, 해당 문장 하위의 모든 문장을 건너뛰고 - while문의 조건식 위치 - for 문의 증감식 위치로 분기한다. |
[Q] 놀이동산에서 열차를 운행한다. 5명이 타면 출발할때, 150 ~ 180이면 열차에 탑승가능하다면
<실행>
키는 얼마? 150
1명 탑승
키는 얼마? 149
1명 탑승
키는 얼마? 181
1명 탑승
...
5명 탑승
열차 출발
import java.util.Scanner;
public class Exam14 {
public static void main(String[] args) {
int height;
int count = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("키는 얼마?");
height = scanner.nextInt();
if (height >= 150 && height <= 180)
count +=1; // ++count;
// if(height < 150 || height > 180) continue ==> 탑승 메세지를 쓸 수 없다
// if(!(height < 150 || height > 180)) ++count ==> 해결
// if( 150 <= height <= 180) ==> 오류
System.out.printf("%d 명 탑승\n", guest);
if (count ==5) {
System.out.println("열차 출발");
break;
}
}
}
}
while (count < 5) 인 조건식 가능
if (height >= 150 && height <= 180) | |
가능 | 불가능 |
if (!(height < 150 || height > 180)) ++count; | if(height < 150 || height > 180) continue ==> 탑승 메세지를 쓸 수 없으므로 부적절하다. if(150 <= height <= 180) ==> 오류 : 자바에서는 불가능한 연산이다. |
[Q] 자연수의 합, n! 구하기
1) 자연수의 합
n을 입력: 10
1~10 까지의 합 : 55
import java.util.Scanner;
public class Exam15 {
public static void main(String[] args) {
int n; // 입력을 받기 위한 값
int i = 1; //int n, i =0 ; (0 에대해 한 번 다시 돎)
int sum = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("n을 입력: ");
n = scanner.nextInt();
while (i <= n) {
sum += i;
++i; // i++;
if (i > n){
System.out.printf("1~%d 까지의 합: %d", n, sum);
break;
}
}
scanner.close();
}
}
2) n! 구하기
n은 1~10까지만 입력 가능
n을 입력 : 5
5! = 120
import java.util.Scanner;
public class Exam16 {
public static void main(String[] args) {
int n;
int i =1;
int fac = 1; // 반드시 1로 주어야 한다. 0은 아무리 곱해도 0이다.
Scanner scanner = new Scanner(System.in);
System.out.print("n을 입력 (1~10 까지만 가능): ");
n = scanner.nextInt();
if( n< 1 || n>10) {
System.out.println("1-10까지만 가능");
// System.exit(0); // 강제종료
return; // 메인메소드를 호출한 곳으로 되돌아가라 ==> 프로그램 종료
}
while(i <= n) {
fac *= i;
++i; // i++;
if (i > n){
System.out.printf("%d! = %d", n, fac);
break;
}
}
scanner.close();
}
}
System.exit(0); | return; |
강제종료 | 메인메소드를 호출한 곳으로 되돌아가라 -> 프로그램 종료 |
결국 같은 의미 이다. |
[Q] 구구단
import java.util.Scanner;
public class WhileGugudan {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dan;
int i = 0;
System.out.print("출력할 단:");
dan = scanner.nextInt();
while (i++ < 9)
System.out.println(dan + "*" + i + "=" + (dan * i));
scanner.close();
}
}
'국비 교육 > 백엔드(Java, Spring)' 카테고리의 다른 글
[자바] 반복문 -2 (do-while, for) (0) | 2024.01.18 |
---|---|
[자바] 입력 버퍼 (Buffer) (0) | 2024.01.18 |
[자바] 연산자 Operator -2, Switch (0) | 2024.01.17 |
[자바] 키보드로부터 입력 (0) | 2024.01.16 |