티스토리 뷰

Given the code fragment:

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;
/* line n1 */
System.out.print("The Top element: "+stack[idx]);
}
}

Which code fragment, inserted at line n1, prints The Top element: 30?

 

A. do{
idx++;
System.out.println("idx: "+idx);
}while(idx>=size);

B. while(idx<size){
idx++;


C. do{
idx++;
System.out.println("idx at do="+idx);
}while(idx<size-1); 

D. do{
idx++;
}while(idx<=size); 

E. while(idx<=size-1){
idx++;
}

 

해설:

이 문제는 stack 배열의 30을 출력해야 하니까 인덱스가 2여야 하고 idx가 2인것을 만들어 주는 보기를 찾으면 된다.

바로 보기별 실행을 하면서 정확하게 살펴보자.

A.

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;
do{
idx++;
}while(idx>=size);

System.out.println("idx: "+idx);
System.out.print("The Top element: "+stack[idx]);
}
}

결과:

idx: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Arr67.main(Arr67.java:28)

idx가 3이여서 ArrayIndexOutOFBoundsException이 발생하여 실패.

 

B.

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;

while(idx<size){
idx++;
}

System.out.println("idx: "+idx);
System.out.print("The Top element: "+stack[idx]);
}
}

결과

idx: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Arr67.main(Arr67.java:28)

이것 역시 idx가 3이라서 실패

C.

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;

do{
idx++;
}while(idx<size-1);

System.out.println("idx: "+idx);
System.out.print("The Top element: "+stack[idx]);
}
}

결과:

idx: 2
The Top element: 30

정답

D.

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;

do{
idx++;
}while(idx<=size);

System.out.println("idx: "+idx);
System.out.print("The Top element: "+stack[idx]);
}
}

결과:

idx: 4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Arr67.main(Arr67.java:27)

실패

E.

public class Arr67 {
public static void main(String[] args) {
int[] stack={10,20,30};
int size=3;
int idx=0;

while(idx<=size-1){
idx++;
}

System.out.println("idx: "+idx);
System.out.print("The Top element: "+stack[idx]);
}
}

결과:

idx: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Arr67.main(Arr67.java:27)

실패

 

정답: C

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/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
글 보관함