这里记录一些学习Think in java的笔记,大部分例子取自该书。
1、关于switch:
看2个例子,例子1:
for (int i = 0; i < 3; i++) {
switch (i) {
case 0:
System.out.println("i = " + 0);
case 1:
System.out.println("i = " + 1);
case 2:
System.out.println("i = " + 2);
case 3:
System.out.println("i = " + 3);
}
}
输出结果:
i = 0
i = 1
i = 2
i = 3
i = 1
i = 2
i = 3
i = 2
i = 3
例子2:添加break关键字,
for (int i = 0; i < 3; i++) {
switch (i) {
case 0:
System.out.println("i = " + 0);break;
case 1:
System.out.println("i = " + 1);break;
case 2:
System.out.println("i = " + 2);break;
case 3:
System.out.println("i = " + 3);break;
}
}
输出结果:
i = 0
i = 1
i = 2
造成这差异的原因:
如不添加break关键词,程序会挨个继续执行接下来的case语句,直到遇到break为止。所以例子1中输出了3次3。
2、关于标签
标签对我而言比较陌生,所以编写一个例子助于理解。
语法: 带有冒号的标示符,并且只能在迭代语句之前。
示例代码:
int i = 0;
outer: for (; true;) {
inner: for (; i < 10; i++) {
System.out.println(" i = " + i);
if (i == 2) {
System.out.println("continue");
continue;
}
if (i == 3) {
System.out.println("break");
i++;
break;
}
if (i == 7) {
System.out.println("continue outer");
i++;
continue outer;
}
if (i == 8) {
System.out.println("break outer ");
break outer;
}
if (i == 8) {
System.out.println("break outer");
}
for (int k = 0; k < 5; k++) {
if (k == 3) {
System.out.println("continue inner");
continue inner;
}
}
}
}
示例结果:
i = 0
continue inner
i = 1
continue inner
i = 2
continue
i = 3
break
i = 4
continue inner
i = 5
continue inner
i = 6
continue inner
i = 7
continue outer
i = 8
break outer
标签作用:控制流程的有效手段。