第6課流程控制的陷阱讀書筆記:
1、 switch語句允許的表達式:
()裏只能是如下5種數據類型:byte,short,int,char,enum
絕對不能是String,long,float,double等其他基本類型。
package com.trap;
public class SwitchTest {
public static void main(String[] args) {
int a=5;
switch((int)(a+1.2+0.8)){
case 6:System.out.println("6");break;
case 7:System.out.println("7");break;
case 8:System.out.println("8");break;
default:System.out.println("default");
}
}
}
package com.trap;
enum Season
{
SPRING,SUMMER,FALL,WINTER
}
public class EnumSwitch
{
public static void main(String[] args)
{
Season s = Season.FALL;
switch (s)
{
case SPRING://不可加Seanson.SPRING限定
System.out.println("春天不是讀書天");
break;
case SUMMER:
System.out.println("夏日炎炎正好眠");
break;
case FALL:
System.out.println("秋多蚊蠅");
break;
case WINTER:
System.out.println("冬日冷");
break;
}
}
}
2、 if語句中的else的隱含條件:就是不滿足else之前的條件
3、 儘量不省略循環體的花括號
Java語言規定,for,while,do循環中重複執行的語句不能是一條單獨的局部變量定義語句。
4、 For循環
1、小心for();….
2、掌握循環執行次數要看整個循環過程(過程中改變)
3、浮點數作循環計數器
情況1:無限循環
package com.trap;
public class FloatCount
{
public static void main(String[] args)
{
final int START = 999999999;
//嘗試循環50次,結果無限循環,因爲i的值一直是:1.0E9 而START+50 是1.000006E9
for (float i = START ; i < START + 50 ; i ++)
{
System.out.println("i的值:" + i + new java.util.Date());
}
}
}
原因:
package com.trap;
public class FloatTest
{
public static void main(String[] args)
{
final float f1 = 999999999;
System.out.println(f1);
System.out.println(f1 + 1);
System.out.println(f1 == f1 + 1); //true
}
}
情況2:不執行
package com.trap;
public class FloatCount2
{
public static void main(String[] args)
{
final int START = 999999999;
//嘗試循環20次
for (float i = START ; i < START + 20 ; i ++)
{
System.out.println("i的值:" + i + new java.util.Date());
}
}
}
原因:
package com.trap;
public class FloatTest2
{
public static void main(String[] args)
{
final float f1 = 999999999;
System.out.println(f1);
System.out.println(f1 + 20);
//下面語句輸出true
System.out.println(f1 == f1 + 20);
System.out.println(f1 + 50);
//下面語句輸出false
System.out.println(f1 == f1 + 50);
}
}
4、foreach作循環計數器
循環過程中改變循環變量沒有意義,不會改變集合本身