티스토리 뷰

Given the code fragment:

public class DoWhile89 {
public static void main(String[] args) {
int[] arr= {1,2,3,4};
int i=0;
do {
System.out.print(arr[i]+" ");
i++;
}while(i < arr.length - 1);
}
}

What is the result?

A. 1 2 3 4

followed by an ArrayIndexOutOfBoundsException

B. 1 2 3

C. 1 2 3 4

D. Compilation fails

 

해설:

아래 코드를 보면 이해가 쉬울듯 합니다.

public class DoWhile89 {
public static void main(String[] args) {
int[] arr= {1,2,3,4};
int i=0;
do {
System.out.println("증가전 i="+ i);
System.out.println(arr[i]+" ");
i++;
System.out.println("증가 후 i="+ i);
System.out.println();
}while(i < arr.length - 1);
}
}

결과

증가전 i=0

증가 후 i=1

증가전 i=1

증가 후 i=2

증가전 i=2

증가 후 i=3

첫번째 루프: i가 0 부터 시작해서 인덱스가 1인 배열값을 프린트하고(1) 1증가 while문과 비교(1<4-1,즉 1<3) true

두번째 루프: i가 1 부터 시작해서 인덱스가 2인 배열값을 프린트하고(2) 1증가 while문과 비교(2<4-1,즉 2<3) true

두번째 루프: i가 2 부터 시작해서 인덱스가 3인 배열값을 프린트하고(3) 1증가 while문과 비교(3<4-1,즉 3<3) false

끝.

결과:

1 2 3 

정답: B

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함