1.循環(huán)語(yǔ)句:while,do-while,for
2.分支語(yǔ)句:if-else,switch,
3.跳轉(zhuǎn)語(yǔ)句 break,continue,label: 和return
4.異常處理語(yǔ)句:try-catch-finally,throw
實(shí)踐:
1.循環(huán)語(yǔ)句
while 語(yǔ)句
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
do…while 語(yǔ)句
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
二者區(qū)別,do…while至少循環(huán)一次,而while的表達(dá)式要是為flase的話可以一次也不循環(huán)。再通俗一點(diǎn),do…while就算是括號(hào)里的是flase,人家最少也能do一次。
for語(yǔ)句
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
與上面那兩個(gè)的區(qū)別,for循環(huán)執(zhí)行的次數(shù)是可以在執(zhí)行之前確定的。通俗一點(diǎn)說吧,看這個(gè)例子 for(n=10; n>0; n--)就是在括號(hào)里的時(shí)候,就已經(jīng)知道要循環(huán)10次了。
還有啊,for循環(huán)的部分可以為空的
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
2.分支語(yǔ)句
if/else語(yǔ)句
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
//這段程序輸出:
//April is in the Spring.
// 注意 “||”是或運(yùn)算
switch語(yǔ)句
class Switch {
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
switch語(yǔ)句適合于條件非常多的邏輯
請(qǐng)看上述語(yǔ)句可以混合使用,請(qǐng)看下載例子
如有問題請(qǐng)登陸論壇