티스토리 뷰

Given the code fragment:

public class Switch13 { 
public static void main(String[] args) { 
boolean opt=true;
switch(opt) { 
case true: 
System.out.print("True"); 
break; 
default: 
System.out.print("***"); 
} 
System.out.println("Done"); 
} 
}

Which modification enables the code fragment to print TrueDone?

A. Replace line 5 With String opt="true";

Replace line 7 with case "true":

B. Replace line 5 with boolean opt=1;

Replace line 7 with case 1:

C. At line 9, remove the break statement.

D. Remove the default section.

 

정답: A

해설:

switch() 의 괄호 안에는 boolean이 올 수 없고 정수, 스트링 또는 enum만 올 수 있다.

Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted

그래서 아래처럼 코딩하면 정답이 나온다.

public class Switch13 {
public static void main(String[] args) {
String opt="true";
switch(opt) {
case "true":
System.out.print("True");
break;
default:
System.out.print("***");
}
System.out.println("Done");
}
}

결과:

TrueDone

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