개발자의 공부방/자바

자바 기초] for문, while문, do-while문 등

  • -
728x90
반응형

for문

 

  • 특정한 명령들을 정해진 규칙에 따라 반복처리 할 때 사용하는 제어문이다.
1
2
3
4
for (초기식; 조건식; 증감식) {
    수행할 문장;
}
 
cs

 

 

# 초기식 : 가장 먼저 한번만 수행됨

# 조건식 : 초기식 다음으로 수행되고 루프(loop)가 돌 때마다 한번씩 비교, 반복문을 수행할지 반복문을 벗어날지 결정함.

# 증감식 : 루프를 수행할 때마다 조건식에 비교하기 전에 항상 수행함! 변수값을 증가 또는 감소시켜서 루프를 원활하게 수행시킴.

  

 

 

 

 

 

=====실습 예제=====

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class For_Ex01 {
    public static void main(String[] args) throws IOException {
        int dan = 0;
        System.out.println("간단한 구구단 예제입니다");
        System.out.println("단수 : ");
 
        dan = System.in.read() - 48;
 
        for (int a = 1; a < 10; a++) {
            System.out.println(dan + "*" + a + "=" + (dan * a < 10 ? " """+ (dan * a));
        }
 
    }
}
cs
 
 
 
 

다중 for문

 

  • for문 안에 for문이 있는 경우
1
2
3
4
5
6
for (초기식; 조건식; 증감식){
    for(초기식; 조건식; 증감식){
        수행할 문장;
    }
    수행할 문장;
}
cs

 

 

 

 

 

=====실습 예제=====

 

1
2
3
4
5
6
7
8
9
10
11
12
public class For_Ex02 {
 
    public static void main(String[] args) {
        System.out.println("다중 for문 구구단 실습!");
        for (int i = 1; i < 10; i++) {
            for (int j = 1; j < 10; j++) {
                System.out.println(i + "*" + j + "=" + (j * i) + " ");
            }
            System.out.println();
        }
    }
}
cs

 

 

 

 

 

while문

 

  • for문과 유사함. 특정 명령들을 반복적으로 처리
  • for문은 반복횟수를 정확히 알고 있는 경우에 많이 사용하고 while문은 반복횟수를 정확히 알지 못할 때 사용함.
  • 무한루프에 빠질 수 있으므로 주의

 

 

 

 

 

 

1
2
3
while(조건식)
    수행할 문장;
}
cs

 

 

 

 

 

 

 

 

=====실습 예제=====

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.java.basic;
 
public class whiel_Ex01 {
    public static void main(String[] args) {
        System.out.println("1~100까지 합을 구해보자!");
        int i=0;
        int sum=0;
        while(i<100) {
            i++;
            sum+=i;
        }
        System.out.println();
        System.out.println("1부터 100까지의 합은 : "+sum+" 입니다! 우왕!");
    }
}
cs

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class while_Ex02 {
 
    public static void main(String[] args) {
        System.out.println("달력 모양으로 숫자를 출력해보자!");
        int i = 1;
        while(i<=31) {
            if(i % 7 == 0) {
                System.out.println(i);
            }else {
                System.out.print(i+"\t");
            }
            i++;
        }
        System.out.println();
    }
}
cs

 

 

 

 

 

do ~ while문

 

  • while문과는 달리 do { }를 무조건 한 번 수행한 후 값을 비교.
  • while(조건식) 뒤에 ;(세미콜론)을 생략하면 오류가 발생된다.
  • 사용자의 입력제한을 위해서 주로 사용
1
2
3
do {
    수행할 문장;
}while(조건식);

cs

 

 

 

 

 

=====실습 예제=====

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class do_while_Ex01 {
    public static void main(String[] args) throws IOException {
        System.out.println("사용자 메뉴 입력하기!");
        
        int menu = 0;
        do {
            System.out.println("1. 회원가입");
            System.out.println("2. 회원조회");
            System.out.println("3. 회원탈퇴");
            System.out.println("0. 프로그램 종료");
            System.out.println("메뉴선택 : ");
            menu = System.in.read() - 48;
        }while(menu != 1 && menu != 2 && menu!=3 && menu!=0);
        System.out.println("선택한 메뉴는: "+menu);
    }
}
cs

 

 

 

 

 

break문

 

  • 반복문(for, while), switch문에서 쓰임
  • 강제적으로 해당 반복문을 빠져나갈 때 쓰이는 제어문
  • break문을 만날 때 가장 가까운 반복문 한 개를 탈출함
1
2
3
4
for(초기식;조건식; 증감식){
    수행할 문장
    break;
}
cs

 

 

 

 

 

=====실습 예제=====

 

1
2
3
4
5
6
7
8
9
10
11
12
public class break_Ex01 {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            System.out.println(" " + i);
            if (i == 20)
                break;
            i++;
        }
        System.out.println();
    }
}
cs

 

 

 

 

 

break label문

  • break label문은 break문과 달리 여러개의 반복문을 빠져나갈 떄 사용함.
1
2
3
4
5
6
레이블명: for(초기식; 조건식; 증감식) {
            for(초기식; 조건식; 증감식) {
                수행문;
                    break 레이블명; //레이블명이 있는 곳까지 빠져나감.
    }
}
cs
 

 

 

 

 

=====실습 예제=====

 
 
1
2
3
4
5
6
7
8
9
10
11
12
public class break_Ex01 {
    public static void main(String[] args) {
        int i = 0;
        while (i < 100) {
            System.out.println(" " + i);
            if (i == 20)
                break;
            i++;
        }
        System.out.println();
    }
}
cs

 

 

 

 

 

Contine 문

  • 반복문에서 사용되며 어느 특정 문장이나 여러 문장을 건너뛰고자 할 떄 사용됨.

 

1
2
3
4
for(초기식; 조건식; 증감식) {
    continue;
    수행문;
}
cs

 

 

 

 

 

 

=====실습 예제=====

 

1
2
3
4
5
6
7
8
9
10
public class Continue_Ex01 {
 
    public static void main(String[] args) {
        for(int i=0; i<=20; i++) {
            if(i % 2 == 0continue;
            System.out.println(i+" "); //홀수만 출력
        }
        System.out.println("");
    }
}
cs

 

 

 

 

 

Contine label문

  • continue label 문은 레이블까지 수행시점이 이동함.
1
2
3
4
5
6
레이블명: for(초기식; 조건식; 증감식) {
            for(초기식;조건식; 증감식) {
                수행문;
                continue 레이블명;
    }
}
cs

 

 

 

 

 

=====실습 예제=====

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Continue_Label_Ex02 {
 
    public static void main(String[] args) {
        F1: for (int i = 0; i < 5; i++) {
            F2: for (int j = 0; j < 3; j++) {
                if (j == 1) {
                    continue F1;
                }
                System.out.println(j + "x" + i + " ");
            }
            System.out.println();
        }
    }
}
cs

 

 

 

 

 

향상된 for문

  • 자바 5.0에 추가된 for문
  • for문의 반복 카운트 변수가 배열의 인덱스일 경우 사용
  • 카운트 변수를 제어해야 할 경우에는 사용할 수 없음.
1
2
3
for(배열 내부의 변수 자료형 변수 : 배열이름) {
    수행할 문장;
}
cs

 

 

 

 

 

=====실습 예제=====

 

 

1
2
3
4
5
6
7
8
9
10
11
12
public class upswing_for_Ex01 {
 
    public static void main(String[] args) {
        String[] arr = {"AA","BB","CC","DD","EE"};
        for(String s : arr) {
            System.out.println("배열의 값들은 ? "+s);
        }
        for(int i=0; i<arr.length;i++) {
            System.out.println("배열의 값들은 ? "+arr[i]);
        }
    }
}
cs

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.