[java] ocajp 문제 풀이 - do while 67
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