티스토리 뷰

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

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
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
글 보관함