admin 管理员组

文章数量: 1184232


2024年3月9日发(作者:c语言定义二维数组省略下标)

重点题型:switch和case,tye和 catch和finally题 1/4

 总结

1、 在try-catch-finally中,有了try后,catch和finally只有其中之一也可以;

2、 在try-catch-finally中,当出现异常时,程序执行了finally块后跳出程序(有finally块的话),不再执行下面语句(包括下面包含有的catch块—下面有例子),当在catch块中遇到();,则跳出程序,连finally块也不执行;

3、 switch的判断的条件必须是一个byte、short、int、char型值;

4、 case中如果没有break语句则将无判断继续执行其它case (下面有例子);如果没有任何值符合case列出的判断,则执行default的语句,default是可选的,如果没有default而又没有任何值匹配case中列出的值则switch不执行任何语句。

 62. public class SwitchTest{

public static void main(String[] args){

3) n("value="+switchIt(4));

}

public static int switchIt(int x){

int j=1;

switch(x){

case 1: j++;

case 2: j++;

case 3: j++;

case 4: j++; //开始j=2;

case 5: j++; //j=3

default: j++; //j=4

}

return j+x; //等于 4+4=8

}

}

what is the output from line 3?

A. value=3 B. value=4 C. value=5 D. value=6

答案:F

 public class Foo{

public static void main(String args[]){

try{return;}

finally{ n("Finally");}

}

}

what is the result?

A. print out nothing

B. print out "Finally"

C. compile error

答案:B

问题:他这里没有catch{}语句不会编译错误吗?E. value=7 F. value=8

重点题型:switch和case,tye和 catch和finally题 2/4

回答:catch和finally有其中之一就可以。

 5. public class Test{

public static String output="";

public static void foo(int i){

try {

if(i==1){

throw new Exception();

}

output +="1";

}

catch(Exception e){

output+="2";

return;

}

finally{

output+="3";

}

output+="4";

}

public static void main(String args[]){

foo(0);

foo(1);

24)

}

}

what is the value of output at line 24?

答案:13423

解析:在try-catch-finally中,当出现异常时,程序执行了finally块后跳出程序,不再执行下面语句,当在catch块中遇到();,则跳出程序,连finally块也不执行(如下题);

 public class Foo{

public static void main(String[] args){

try{(0);}

finally{n("Finally");}

}

}

what is the result?

out nothing

out "Finally"

答案:A

 public static void main(String args[]){

try{

methodA();

}catch(IOException e){

重点题型:switch和case,tye和 catch和finally题 3/4

n("caught IOException");

}catch(Exception e){

n("caught Exception");

}

}

}

If methodA() throws a IOException, what is the result?

答案:caught IOException

 55、Given the following code fragment:

1) switch(m)

2) { case 0: n("case 0");

3) case 1: n("case 1"); break;

4) case 2:

5) default: n("default");

6) }

Which value of m would cause "default" to be the output?

A. 0 B. 1

C. 2

D. 3

答案:(cd)

题目:给出下面的代码片断:

m为哪些值将导致"default"输出。

此题考察switch语句的用法,switch的判断的条件必须是一个int型值,也可以是byte、short、char型的值,case中需要注意的是一个case后面一般要接一个break语句才能结束判断,否则将继续执行其它case而不进行任何判断,如果没有任何值符合case列出的判断,则执行default的语句,default是可选的,可以没有,如果没有default而又没有任何值匹配case中列出的值则switch不执行任何语句。

 int i=9;

switch (i) {

default:

n("default");

case 0:

n("zero");

break;

重点题型:switch和case,tye和 catch和finally题 4/4

case 1:

n("one");

case 2:

n("two");

}

1) default

2) default, zero

3) error default clause not defined

4) no output displayed

答案:2)

解析:default任意位置放,在这里执行了default,没遇到到break,没跳出循环,然后执行case 0,输出zero,遇到break,然后跳出。


本文标签: 语句 判断 没有 执行 跳出