1. While, Do-While 문
while(조건){ 내용 }
do{
내용
} while(조건)
while문은 조건이 true일 경우 내용을 실행하고 다시 조건을 확인한다, false일 경우는 반복문에서 나온다.
do-while문은 먼저 내용을 실행하고나서 조건을 확인하여 반복을 실행할지 결정한다.
일반적으로 while 조건을 true로 설정해놓고 무한 반복을 주고
원하는 값이 나오면 break; 를 사용하여 반복을 종료한다.
아래의 예제로 while의 사용법을 확인하자
package chap02.ex07.whileEx;
public class WhileStmt {
public static void main(String[] args) throws InterruptedException {
// while은 조건이 true면 계속 돈다.
int i = 1;
while(true){
System.out.println(i + "회 반복");
i++;
if(i >= 777778) {
break;
}
}
// 만약 break를 쓰지 않았다면 오류 코드 unreachable code가 뜨고 아래를 실행 할 수 없다.
System.out.println("반복 종료");
}
}
아래의 예제는 do-while문을 이용한 채팅이다.
package chap02.ex07.whileEx;
import java.util.Scanner;
public class DoWhileStmt {
public static void main(String[] args) {
System.out.println("000님이 입장 하셨습니다.");
System.out.println("q를 입력하면 종료됩니다.");
String msg = "";
Scanner scanner = new Scanner(System.in);
// do while은 일단 저지르고 조건을 본다.
do {
System.out.print(">");
msg = scanner.nextLine();
System.out.println("당신 >" + msg);
}while(!msg.equals("q"));
System.out.println("@@@@");
System.out.println("채팅이 종료되었습니다.");
System.out.println("@@@@");
scanner.close();
}
}
'개념 및 코딩 > 02.조건문, 반복문' 카테고리의 다른 글
| [JAVA]02-05.반복 제어 continue, break (0) | 2018.08.22 |
|---|---|
| [JAVA]02-03.For 반복문 (0) | 2018.08.22 |
| [JAVA]02-02.Switch Case (0) | 2018.08.22 |
| [JAVA]02-01.if 조건문 (0) | 2018.08.22 |