
for (초기화식; 조건식; 증감식) { 로직 }
Java의 For문 역시 JavaScript의 For문과 완전히 똑같다.
조건이 만족되는 동안 { 로직 }이 반복된다.
// 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);
}
}
}
// while문
while (조건) { 로직 }
// do-while문
do { 로직 } while (조건)
Java의 While문 역시 JavaScript의 While문과 완전히 똑같다.
조건이 만족되는 동안 { 로직 }이 반복된다.
// 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("올바른 코드명을 입력했습니다.");
}
}