ocjap 문제 해설 - DoWhile 84
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
/* line n1 */
}
}
A. while(x>0) {
x--;
System.out.print(array[x]);
}
B. do {
x--;
System.out.print(array[x]);
}while(x>=0);
C. while(x>=0) {
System.out.print(array[x]);
x--;
}
D. do {
System.out.print(array[x]);
--x;
}while(x>=0);
E. while(x>0) {
System.out.print(array[--x]);
}
Which two code fragments can be independently inserted at line n1 to enable the code to print the elements of the array in reverse order? (Choose two.)
정답: AE
해설:
보기를 하나씩 대입해서 결과를 보면 쉽게 이해가 될것이다.
A.
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
while(x>0) {
x--;
System.out.print(array[x]);
}
}
}
결과:
5040302010
B.
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
do {
x--;
System.out.print(array[x]);
}while(x>=0);
}
}
결과:
5040302010Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Array84.main(Array84.java:16)
while(x>=0) 이기 때문에 0일때도 do가 실행이 되고 x-- 에 의해 x가 -1 이기 되기 때문이다.
C.
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
while(x>=0) {
System.out.print(array[x]);
x--;
}
}
}
결과:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Array84.main(Array84.java:23)
처음 x는 5로 시작되기 때문에
D.
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
do {
System.out.print(array[x]);
--x;
}while(x>=0);
}
}
결과:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Array84.main(Array84.java:30)
처음 x는 5로 시작되기 때문에
E
public class Array84 {
public static void main(String[] args) {
int array[]= {10,20,30,40,50};
int x=array.length;
while(x>0) {
x--;
System.out.print(array[x]);
}
}
}
결과:
5040302010