int i;
for(i=1; i<=10; i++) {
System.out.print(i); //12345678910
}
System.out.println("탈출 i = "+ i); //탈출 i = 11
int a = 0;
while(a<10) {
a++;
System.out.print(a+" ");
}
System.out.println(); //1 2 3 4 5 6 7 8 9 10
int a = 0;
do {
a++;
System.out.print(a+" ");
}while(a<10);
System.out.println(); //1 2 3 4 5 6 7 8 9 10
break
만나는 즉시 반복문 전체 탈출(switch문에서도 사용됨)
public class Main {
public static void main(String[] args) {
for(int i=1; i<5; i++){
if(i==3) break;
System.out.println(i);
}
System.out.println("반복문 끝!");
}
}
//1
//2
//반복문 끝!
continue
만나면 해당 반복부분 탈출 후 다음반복실행
public class Main {
public static void main(String[] args) {
for(int i=1; i<5; i++){
if(i==3) continue;
System.out.println(i);
}
System.out.println("반복문 끝!");
}
}
//1
//2
//4
//반복문 끝!```
배열 내의 모든 값을 반복하는 for문의 향상된 형태.
인덱스 값이 필요하지 않을 때 간결하고 유용하다.
형식
for (요소타입 변수명: 반복대상) {
실행영역;
}
EX)
String[] arrFruit = {"banana", "tomato", "apple"};
for(String fruit:arrFruit) {
System.out.print(fruit+" "); //banana tomato apple
}