第5章 流程控制-思考题
1、运行以下代码,将得到什么打印结果?
int i=3;
int j=0;
double k=3.2;
if(i<k)
if(i==j)
System.out.println(i);
else
System.out.println(j);
else
System.out.println(k);
打印结果:0。
2、以下代码能否编译通过?如可以,运行将得到什么结果?
int i=4;
switch(i){
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
可以通过编译,结果为:
default
zero
3、以下哪些代码是合法的?
(a)
int i;
for(i=5,int j=10;i<10;j--){}
for中初始化语句非法。
(b)
int i,j;
for(i=0,j=10;i<10,j>0;i++,j--){}
for中条件语句非法。
(c)
int k,k;
for(i=0,k=9;(i<10&&k>0);i++,k--){}
合法
(d)
int i,j;
for(i=0;j=10;i<10;i++,j--){}
初始化语句非法。
4、运行以下代码,将得到什么打印结果?
int i=1;
switch(i){
default:
System.out.println("default");
case 0:
System.out.println("zero");
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
one
two
5、以下代码哪些是合法的?
(a)
float x=1;
switch(x){
case 1:
System.out.println("Got a 1");
}
非法,float型数据不能匹配switch的int型。
(b)
long x=1;
switch(x){
case 1:
System.out.println("Got a 1");
break;
}
非法,long型数据不能匹配switch的int型。
(c)
byte x=1;
switch(x){
case 1/1:
System.out.println("Got a 1");
}
合法。
(d)
int x=1;
int c=1;
switch(c){
case x:
System.out.println("Got a 1");
break;
}
非法,x为变量,无法匹配case中常量。
(e)
short x=1;
switch(x){
case 3.2/3:
System.out.println("Got a 1");
}
非法,3.2/3结果为浮点型数据不能匹配switch的int型。
(f)
short x=1;
switch(x){
case 1,2,3:
System.out.println("Got a 1");
break;
}
非法,case中1,2,3表达式非常量。
6、以下代码能否编译通过?如可以,运行为什么结果?
public class MySwitch{
public static void main(String[] args){
MySwitch ms=new MySwitch();
ms.amethod();
}
public void amethod(){
for(int a=0,b=0;a<2;b=++a,System.out.println("b="+b)){
System.out.println("a="+a);
}
}
}
打印结果:
a=0;
b=1;
a=1;
b=2;
7、以下代码能否编译通过?如可以,运行为什么结果?
void looper(){
int x=0;
one:
while(x<10){
two:
System.out.println(++x);
if(x>3)
break two;
}
}
打印结果:
1
2
3
4
5
6
7
8
9
8、以下代码能否编译通过?如可以,运行为什么结果?
public class Hope{
public static void main(String[] args){
Hope h=new Hope();
}
protected Hope(){
int i=1;
do{
System.out.println(i);
}while(++i<3);
}
}
打印结果为:
1
2