본문 바로가기
Java (자바)

쉽게 따라하는 Java (자바) 독학 _ 제어문 _ 반복문 (while)

by Ecoder 2022. 12. 6.

 Java (자바) 독학 제어문 _ 반복문 (while)

 

1. 반복문 while

  - 조건에 맞는 경우 반복적으로 명령을 수행

  - 조건에 맞지 않는 경우 명령을 수행하지 않음

  - 정확히 몇 번 반복해야 하는지 모를 때 사용

 

  - while문 관련 명령어

     1) do: 무조건 1회 명령을 수행

     2) while: 조건에 맞는 경우 명령을 수행

 

  - while문 관련 명령어 조합 (2가지)

     1) while 단독 사용

     2) do + while

 

  - while문 사용 형태

      1) while 단독 사용

              while (조건식) {

                   명령문 들...

              }

 

      2) do + while  --> 조건식에 맞는 경우 do 블록에 있는 명령문 실행

             do {

                  명령문 들...

              }

             while (조건식);

 

 

2. 반복문 while Test

 

Class Name: WhileTest_01

public static void main(String[] args) 체크

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
public class WhileTest_01 {
 
    public static void main(String[] args) {
 
        int i = 0;
 
        while(true) {
            System.out.println(i++);
            if (i > 10) {
                break;
            }
        }
    }
 
}
 
cs

 

 

 

저장(ctrl + s) 후 F11을 눌러 출력되는 내용 확인하기

 

 

 

3. 테스트해 보세요

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;
 
public class WhileTest_01 {
 
 
    public static void main(String[] args) {
 
        int i = 0;        
        int value = 0;
 
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("정수를 입력하세요: ");
        value = scanner.nextInt();
 
 
        while (i < 9) {
            ++i;
            System.out.println(value + "*" + i + "=" + (value * i));
        }
 
    }
 
}
cs

 

 

4. 과제

자동으로 1단부터 9단까지 출력되는 구구단을 만들어 보세요.

반응형

댓글