1. For문

for (초기화식; 조건식; 증감식) { 로직 }

JavaFor문 역시 JavaScriptFor문과 완전히 똑같다.
조건이 만족되는 동안 { 로직 }이 반복된다.

// for문 예시

public class ForExample {
    // 18 : for문 : for(){}
    static void main(String[] args) {
        // 구구단 2단 결괏값 출력
        for (int i = 1; i < 10; i++) {
            int result = 2 * i;
            System.out.println(result);
        }
    }
}

2. While문

// while문
while (조건) { 로직 }

// do-while문
do { 로직 } while (조건)

JavaWhile문 역시 JavaScriptWhile문과 완전히 똑같다.
조건이 만족되는 동안 { 로직 }이 반복된다.

// while문 예시

import java.util.Scanner;

public class WhileExample {
    // 19 : while문
    static void main(String[] args) {
        // 19-1 : while () {}
        String password = "aaaa4321";
        Scanner scanner1 = new Scanner(System.in);
        System.out.println("비밀번호는? : ");
        String input1 = scanner1.nextLine();

        while (input1.equals(password) != true) {
            System.out.println("비밀번호가 틀렸습니다. 다시 입력하세요!");
            input1 = scanner1.nextLine();
        }
        System.out.println("로그인 되었습니다!");

        // 19-2 : do {} while ()
        String codeName = "coderen";
        Scanner scanner2 = new Scanner(System.in);
        String input2;

        do {
            System.out.println("코드명을 입력하세요!");
            input2 = scanner2.nextLine();
        } while (input2.equals(codeName) != true);
        System.out.println("올바른 코드명을 입력했습니다.");
    }
}
profile
매일 성장하는 개발자

0개의 댓글