[Java] looping(반복, 순환)

Date:     Updated:

카테고리:

태그:

java.png

looping 이란?

자바에서 루핑(looping)은 특정 조건이 충족될 때까지 일련의 코드 블록을 반복적으로 실행하는 제어 구조를 의미합니다. 주로 for, while, do-while 문을 사용하여 구현되며, 반복적으로 실행해야 하는 작업을 효율적으로 처리하는 데 사용된다.

for 단독 사용에 대한 흐름을 이해하고 적용하자

  • [for 문 표기식]
  • for(초기식; 조건식; 증감식) {
  • 조건을 만족하는 경우 수행할 구문(반복할 구문)
  • }

1부터 10까지 1씩 증가시키며 10번 i 값을 증가시키는 기본 반복문

package section02.looping;

import java.util.Scanner;

public class A_for {

    public void testSimpleForStatement() {
       
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }

        int j = 1;
        for (; j <= 15; j++) {
            System.out.println(j);
        }
        int k = 1; //이렇게도 할수 있다
        for (; k <= 20; ) {
            System.out.println(k);
            k++;
        }
    }

예제 1 반복해야 하는 내용은?

  • 학생의 이름을 입력받아 변수에 저장
  • 안내문구 출력
  • 저장된 이름 출력
public void testForExample1() {
        Scanner sc = new Scanner(System.in);

        System.out.print("1 번째 학생의 이름을 입력해주세요 : ");
        String student1 = sc.nextLine();
        System.out.println("2 번째 학생의 이름은 " + student1 + "입니다.");
        System.out.print("2 번째 학생의 이름을 입력해주세요 : ");
        String student2 = sc.nextLine();
        System.out.println("3 번째 학생의 이름은 " + student2 + "입니다.");
        System.out.print("3 번째 학생의 이름을 입력해주세요 : ");
        String student3 = sc.nextLine();
        System.out.println("4 번째 학생의 이름은 " + student3 + "입니다.");
        System.out.print("4 번째 학생의 이름을 입력해주세요 : ");
        String student4 = sc.nextLine();
        System.out.println("5 번째 학생의 이름은 " + student4 + "입니다.");
        System.out.print("5 번째 학생의 이름을 입력해주세요 : ");
        String student5 = sc.nextLine();
        System.out.println("6 번째 학생의 이름은 " + student5 + "입니다.");
        System.out.print("6 번째 학생의 이름을 입력해주세요 : ");
        String student6 = sc.nextLine();
        System.out.println("7 번째 학생의 이름은 " + student6 + "입니다.");
        System.out.print("7 번째 학생의 이름을 입력해주세요 : ");
        String student7 = sc.nextLine();
        System.out.println("8 번째 학생의 이름은 " + student7 + "입니다.");
        System.out.print("8 번째 학생의 이름을 입력해주세요 : ");
        String student8 = sc.nextLine();
        System.out.println("9 번째 학생의 이름은 " + student8 + "입니다.");
        System.out.print("9 번째 학생의 이름을 입력해주세요 : ");
        String student9 = sc.nextLine();
        System.out.println("10 번째 학생의 이름은 " + student9 + "입니다.");
        System.out.print("10 번째 학생의 이름을 입력해주세요 : ");
        String student10 = sc.nextLine();
        System.out.println("10 번째 학생의 이름은 " + student10 + "입니다.");

        /* 반복 횟수 1~10까지 1씩 증가하여 총 10번을 반복하였다.*/
        for (int i = 1; i <= 10; i++) {
            System.out.println(i + " 번째의 학생의 이름을 입력해주세요");
            String student = sc.nextLine();
            System.out.println(i + " 번째 학생의 이름은 " + student + "입니다.");
        }
    }

우리가 뭘 반복하는지 확인하여 반복문으로 개선할 수 있다

  • 문장 속에 규칙 찾기
  public void testForExample2() {
     
        int sum2 = 0;
        for (int i = 1; i <= 10; i++) {
            sum2 += i;
        }
        System.out.println("sum2 : " + sum2);
    }

우리가 뭘 반복하는지 확인하여 반복문으로 개산할 수 있다

  • 5~10 사이의 난수를 발생시켜서 1부터 발생한 난수의 합계를 구해보자
public void testForExample3() {
   
        int random = (int) (Math.random() * 6) + 5;

        System.out.println("random : " + random);

        /* 뭔가 더해서 담기 위해 sum 변수를 0으로 초기화 */
        int sum = 0;

        for (int i = 1; i <= random; i++) {
            sum += i;
        }
        System.out.println("1부터 " + random + "까지의 합은 : " + sum);
    }

무엇을 반복하는지 확인하여 반복문으로 개선할 수 있다

  • 키보드로 2~9사이에 구구단을 입력받아
  • 2~9사이에 경우 해당 단의 구구단을 출력하고
  • 그렇지 않은 경우 “반드시 2~9 사이의 양수를 입력해야 한다”
public void printSimpleGugudan() {
    
        Scanner sc = new Scanner(System.in);
        System.out.println("출력할 구구단의 단 수를 입력하세요 : ");
        int dan = sc.nextInt();

        if (dan >= 2 && dan <= 9) {

            for (int su = 1; su <= 9; su++) {
                System.out.println(dan + " * " + su + " = " + (dan * su));
            }

        } else {
            System.out.println("반드시 2~9 사이의 양수를 입력해야합니다.");
        }

        System.out.println("프로그램을 종료합니다.");
    }

중첩된 for문의 후름을 이해하고 적용할 수 있다

  • for 문안에 for 문을 이용할 수 있다
package section02.looping;

import java.util.Scanner;

public class A_nestedFor {


    public void printGugudanFromTwoToNice() {

        for (int dan = 2; dan < 10; dan++) {

            for (int su = 1; su < 10; su++) {

                System.out.println(dan + "*" + su + " = " + (dan * su));
            }

            System.out.println();
        }
    }
}

중첩된 for문의 흐름을 이해하고 적용할 수 있다

  • 단을 2단부터 9단까지 하나씩 증가시킨다
   public void printUpgradeGugudanFromTwoToNine() {

        for (int dan = 2; dan < 10; dan++) {

            /* 설명. 한 단씩 구구단을 출력하는 메소드를 호출하며 인자로 단을 전달한다. */
            printGugudanOf(dan);
            /* 설명. 한 단을 출력하고 한 줄을 띄운다. */
            System.out.println();
        }

    }

매개변수로 전달받은 단을 1 ~ 10까지 곱한 내용을 출력해준다.

public void printGugudanOf(int dan) {

        for (int su = 1; su < 10; su++) {
            System.out.println(dan + " * " + su + " = " + (dan * su));
        }
    }

키보드로 정수 하나를 입력받아 해당 정수만큼 한 행에 ‘*‘을 5개씩 ㅇ출력하세요

 public void printStarInputRowTimes() {
  
        Scanner sc = new Scanner(System.in);
        System.out.println("출력할 행 수를 입력하세요 : ");
        int row = sc.nextInt();

        for (int j = 1; j <= row; j++) {

            printStar(5);
            System.out.println();
        }

    }

while 문은 단독 사용에 대한 흐름을 이해하고 적용할 수 있다

  • [while 문 표현식]
  • 초기식
  • while(조건식) {
  • 조건에 만족하는 경우 수행할 구문(반복할 구문)
  • 증감식
  • }

1부터 10까지 1씩 증가시키면서 10번 i값을 출력하는 기본 반복문

package section02.looping;

import java.util.Scanner;

public class B_while {

    public void testSimpleWhileStatement() {

        int i = 1;
        while (i <= 10) {


            System.out.println(i);
            i++;
        }
    }
}

입력한 문자열에 인덱스를 활용하여 문자 하나씩 출력해보기

  • charAt() : 문자열에서 인덱스에 해당하는 문자를 char형으로 반환하는 기능
  • length : String클래스의 매소드로 문자열의 길이를 int형으로 반환한다
  • index는 0부터 시작하고 마지막 인덱스는 항상 길이보다 한 개 작은 숫자를 가진다.
public void testWhileExample(){

        Scanner sc = new Scanner(System.in);
        System.out.print("문자열 입력 : ");
        String str = sc.nextLine();

        System.out.println("============ for문 =============");
        for(int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            System.out.println(i + " : " + ch);
        }
    }

입력한 문자열에 인덱스를 활용하여 문자 하나씩 출력해보기

public void testWhileExample1(){

        Scanner sc = new Scanner(System.in);
        System.out.print("문자열 입력 : ");
        String str = sc.nextLine();

        System.out.println("============ while문 =============");
        int index = 0;
        while(index < str.length()){

            char ch = str.charAt(index);

            System.out.println(index + " : " + ch);

            index++;
        }
    }

중첩된 While문의 흐름을 이해하고 적용할 수 있다.

  • while문으로 구구단 출력하기
    public void testWhileExample2(){
        /*중첩된 While문의 흐름을 이해하고 적용할 수 있다.*/
        /*while문으로 구구단 출력하기*/
        int dan = 2;
        while (dan<=10){

            int su = 1;
            while (su<10){

                System.out.println(dan + " * "+ su + " = " + (dan*su));
                su++;
            }

            dan++;

        }
    }

do-while 문 단독 사용에 대한 흐름을 이해하고 적용할 수 있다

  • [do-while 문 표현식]
  • 초기식;
  • do {
  • 1회차에는 무조건 실행하고 이후에는 조건식을 확인하여조건을 만족하는 경우 수행할 구문(반복할 구문);
  • 증강식;
  • }while[조건식]
package section02.looping;

import java.util.Scanner;

public class C_doWhile {

    public void testSimpleDoWhileStatment() {

        do {

            System.out.println("최초 한번 동작함///");
        } while (false);
        System.out.println("반복문 종료 확인...");
    }
}

do-while 문의 흐름을 이해하고 적용할 수 있다

  • 키보드로 문자열 입력을 받아 반복적으로 출력
  • 단 exit가 입력되면 반복문은 종료한다
 public void testDoWhileExample(){
    
        Scanner sc = new Scanner(System.in);
        String str = "";

        do{

            System.out.println("문자열을 입력하세요 : ");
            str = sc.nextLine();
            System.out.println(str);

            /* equals : 문자열은 == 비교가 불가능하다. 문자열은 문자열이 같은지 비교하는 기능*/
        }while(!str.equals("exit"));

        System.out.println("프로그램을 종료합니다.");

    }

자 이번에도 전체를 Application을 만들어 실행해보자

package section02.looping;

import java.util.Scanner;

public class Application {

    public static void main(String[] args) {

        A_for a = new A_for();
        //a.testSimpleForStatement();
        //a.printSimpleGugudan();
        A_nestedFor an = new A_nestedFor();
        //an.printGugudanFromTwoToNice();
        //an.printStarInputRowTimes();
        //an.printTriangleStars();

        B_while anr = new B_while();
        //anr.testSimpleWhileStatement();
        //anr.testWhileExample1();
        // anr.testWhileExample1();
        C_doWhile c = new C_doWhile();
        //c.testSimpleDoWhileStatment();
        //c.testDoWhileExample();
    }

}
  • 결과값

a.testSimpleForStatement();

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

a.printSimpleGugudan();

출력할 구구단의 단 수를 입력하세요 : 
4
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
4 * 5 = 20
4 * 6 = 24
4 * 7 = 28
4 * 8 = 32
4 * 9 = 36
프로그램을 종료합니다.

an.printGugudanFromTwoToNice();

2*1 = 2
2*2 = 4
2*3 = 6
2*4 = 8
2*5 = 10
2*6 = 12
2*7 = 14
2*8 = 16
2*9 = 18

3*1 = 3
3*2 = 6
3*3 = 9
3*4 = 12
3*5 = 15
3*6 = 18
3*7 = 21
3*8 = 24
3*9 = 27

4*1 = 4
4*2 = 8
4*3 = 12
4*4 = 16
4*5 = 20
4*6 = 24
4*7 = 28
4*8 = 32
4*9 = 36

5*1 = 5
5*2 = 10
5*3 = 15
5*4 = 20
5*5 = 25
5*6 = 30
5*7 = 35
5*8 = 40
5*9 = 45

6*1 = 6
6*2 = 12
6*3 = 18
6*4 = 24
6*5 = 30
6*6 = 36
6*7 = 42
6*8 = 48
6*9 = 54

7*1 = 7
7*2 = 14
7*3 = 21
7*4 = 28
7*5 = 35
7*6 = 42
7*7 = 49
7*8 = 56
7*9 = 63

8*1 = 8
8*2 = 16
8*3 = 24
8*4 = 32
8*5 = 40
8*6 = 48
8*7 = 56
8*8 = 64
8*9 = 72

9*1 = 9
9*2 = 18
9*3 = 27
9*4 = 36
9*5 = 45
9*6 = 54
9*7 = 63
9*8 = 72
9*9 = 81

an.printStarInputRowTimes();

출력할 행 수를 입력하세요 : 
3
*****
*****
*****

an.printTriangleStars();

출력할 줄 수를 입력하세요 : 2
*
**

anr.testSimpleWhileStatement();

1
2
3
4
5
6
7
8
9
10

C_doWhile c = new C_doWhile();

문자열 입력 : 아
============ while문 =============
0 : 아

c.testSimpleDoWhileStatment();

최초 한번 동작함///
반복문 종료 확인...

c.testDoWhileExample();

문자열을 입력하세요 : 
안녕하세요
안녕하세요
문자열을 입력하세요 : 
exit
exit
프로그램을 종료합니다.

계속 입력해보고 출력해보고 연습연습!!

Java 카테고리 내 다른 글 보러가기

댓글 남기기