멍발자의 개발
반복 처리 본문
for문
for (카운터변수, 반복처리조건식, 업데이트식) {
반복처리할 내용
}
public class ForLoop {
public static void main(String[] args) {
for(int i = 0; i < 3; i++) {
System.out.println("반복하자 Loop!");
}
}
}
* 반복처리할 횟수를 알고 있다면 for문을 사용하는 것이 간결하고 좋다.
while문
while (조건식) {
반복 실행 내용
}
package chap07;
public class WhileLoop {
public static void main(String[] args) {
// while문 제어하는 변수 i를 선언하고 1로 초기화
int i = 0;
while (i <= 4) {
System.out.println("반복하자 WhileLoop!");
i++;
}
}
}
//결과
반복하자 WhileLoop!
반복하자 WhileLoop!
반복하자 WhileLoop!
반복하자 WhileLoop!
반복하자 WhileLoop!
break continue문
import java.util.Scanner;
public class BreakStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//카운터 변수
int count = 0;
System.out.println("===== 반복 시작 =====");
while(true){
System.out.print("반복을 시작하려면 'y'를 눌러주세요.");
String result = sc.nextLine();
//입력 판정
if(result.equals("y")){
//카운트 1증가
count++;
System.out.println(count+"번째 반복됨");
System.out.println();
}else{
System.out.println("y이외의 "+result+"가 입력되었으므로 종료합니다.");
break;
}
}
System.out.println("==== 반복 종료 =====");
}
}
// 결과
===== 반복 시작 =====
반복을 시작하려면 'y'를 눌러주세요.y
1번째 반복됨
반복을 시작하려면 'y'를 눌러주세요.y
2번째 반복됨
반복을 시작하려면 'y'를 눌러주세요.y
3번째 반복됨
반복을 시작하려면 'y'를 눌러주세요.d
y이외의 d가 입력되었으므로 종료합니다.
==== 반복 종료 =====
** 반복 처리 내에 포함시켜 기술할 수 있는 것은 if문 뿐이다.
'STUDY > Java' 카테고리의 다른 글
객체 지향 언어 (0) | 2022.03.21 |
---|---|
메소드 (0) | 2022.03.18 |
프로그램 계산과 조건 분기 (0) | 2022.03.15 |
변수 (0) | 2022.03.15 |
[Java 기본 프로그래밍] Hello World! 만들기 (0) | 2022.03.14 |
Comments