摘要:源文件中的語(yǔ)句通常按照它們出現(xiàn)的順序從上到下執(zhí)行。但是,通過(guò)使用控制流語(yǔ)句,可以使您的程序能夠有條件地執(zhí)行特定的代碼塊伊者。本文介紹Java中的控制流語(yǔ)句英遭,涵蓋了分支結(jié)構(gòu)(if、if-else和switch)和循環(huán)結(jié)構(gòu)(for亦渗、while和do-while)贪绘。
一.分支結(jié)構(gòu)
1.if語(yǔ)句
??if語(yǔ)句會(huì)與其后的第一條語(yǔ)句或代碼塊結(jié)合,且只有當(dāng)判斷條件為true時(shí)才執(zhí)行語(yǔ)句或代碼塊央碟。例如,自行車只有在運(yùn)動(dòng)的時(shí)候才可以減速均函,就像下面這樣:
void applyBrakes() {
if (isMoving){
currentSpeed--;
}
}
??如果判斷條件為false亿虽,也就是自行車處于靜止?fàn)顟B(tài)時(shí),將會(huì)跳過(guò)if語(yǔ)句后面的語(yǔ)句或代碼塊苞也。
??如果if語(yǔ)句后只有一條需要執(zhí)行的語(yǔ)句洛勉,既可以使用大括號(hào),也可以不使用如迟。不過(guò)按照慣例來(lái)說(shuō)收毫,任何時(shí)候都應(yīng)該使用大括號(hào),這樣可以避免有時(shí)因?yàn)橥洿罄ㄌ?hào)而帶來(lái)的一些邏輯錯(cuò)誤殷勘。for此再、while語(yǔ)句也是同理。
2.if-else語(yǔ)句
??if語(yǔ)句只是指出了當(dāng)判斷條件為true時(shí)需要執(zhí)行的語(yǔ)句玲销。使用if-else語(yǔ)句可以同時(shí)指定當(dāng)判斷條件為true和false時(shí)應(yīng)該執(zhí)行的語(yǔ)句输拇。當(dāng)自行車沒(méi)有處于運(yùn)動(dòng)狀態(tài)時(shí),可以簡(jiǎn)單地輸出一條信息:
void applyBrakes() {
if (isMoving){
currentSpeed--;
} else {
System.out.println("The bicycle has already stopped!");
}
}
??下面的程序根據(jù)分?jǐn)?shù)來(lái)給出對(duì)應(yīng)的等級(jí):
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
??該程序最終的輸出為:
Grade = C
??雖然testscore滿足很多條件贤斜,例如76>=70和76>=60等策吠,但是,一旦滿足了一個(gè)條件瘩绒,就會(huì)執(zhí)行對(duì)應(yīng)的語(yǔ)句(grade = 'C';)并跳過(guò)剩余條件猴抹。
3.switch語(yǔ)句
??與if和if-else語(yǔ)句不同,switch語(yǔ)句可以有許多可能的執(zhí)行路徑锁荔。例如下面的代碼將會(huì)使用switch語(yǔ)句根據(jù)month的值來(lái)輸出對(duì)應(yīng)的月份:
public class SwitchDemo1 {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";break;
case 2: monthString = "February";break;
case 3: monthString = "March";break;
case 4: monthString = "April";break;
case 5: monthString = "May";break;
case 6: monthString = "June";break;
case 7: monthString = "July";break;
case 8: monthString = "August";break;
case 9: monthString = "September";break;
case 10: monthString = "October";break;
case 11: monthString = "November";break;
case 12: monthString = "December";break;
default: monthString = "Invalid month";break;
}
System.out.println(monthString);
}
}
??該程序?qū)?huì)輸出:
August
??switch語(yǔ)句的判斷條件是一個(gè)變量或表達(dá)式蟀给,它的類型可以是byte,short阳堕,char和int以及它們的包裝類(Character坤溃,Byte,Short嘱丢,和Integer)薪介,還可以是字符串和枚舉類型,case后面是這些類型的字面量越驻。
??default語(yǔ)句用來(lái)處理當(dāng)所有case標(biāo)簽都不滿足的情況汁政。break語(yǔ)句用來(lái)退出switch塊道偷。如果一個(gè)case語(yǔ)句最后沒(méi)有使用break,將會(huì)執(zhí)行下一個(gè)case的語(yǔ)句而不進(jìn)行判斷记劈,直到遇到break或switch塊結(jié)束勺鸦。下面的例子根據(jù)month的值來(lái)輸出季節(jié):
public class SwitchDemo2 {
public static void main(String[] args) {
int month = 5;
switch(month) {
case 2:
case 3:
case 4: System.out.println("Spring");
case 5:
case 6:
case 7: System.out.println("Summer");
case 8:
case 9:
case 10: System.out.println("Autumn");
case 11:
case 12:
case 1: System.out.println("Winter");
}
}
}
??該程序?qū)?huì)輸出:
Summer
??其實(shí)無(wú)論month的值是5,6還是7目木,都會(huì)輸出Summer换途,因?yàn)閏ase 5和case 6都沒(méi)有break語(yǔ)句,即使匹配到了它們刽射,程序也還是會(huì)進(jìn)入case 7军拟。
二.循環(huán)結(jié)構(gòu)
1.while語(yǔ)句和do-while語(yǔ)句
??當(dāng)判斷條件為true時(shí),while語(yǔ)句將會(huì)重復(fù)執(zhí)行代碼塊中的內(nèi)容誓禁,直到判斷條件為false懈息。它的語(yǔ)法如下:
while (expression) {
statement(s)
}
??下面的程序使用while循環(huán)打印出1~10:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
??可以使用以下while語(yǔ)句實(shí)現(xiàn)無(wú)限循環(huán):
while (true){
// your code goes here
}
??Java也支持do-while循環(huán),語(yǔ)法如下:
do {
statement(s)
} while (expression);
??do-while循環(huán)和while循環(huán)之間的區(qū)別在于它在執(zhí)行完代碼塊中的語(yǔ)句之后進(jìn)行判斷摹恰,而不是在循環(huán)開(kāi)始前進(jìn)行判斷辫继。也就是說(shuō),循環(huán)體中的代碼至少會(huì)執(zhí)行一次俗慈。下面的程序使用do-while循環(huán)打印出1~10:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
2.for循環(huán)
??for循環(huán)可以控制循環(huán)的次數(shù)姑宽,它的的語(yǔ)法如下:
for (initialization; condition; increment) {
statement(s)
}
??使用for循環(huán)時(shí),需要注意:
- initialization通常用來(lái)更初始化計(jì)數(shù)器闺阱,它只在循環(huán)開(kāi)始前執(zhí)行一次低千。
- condition時(shí)每一次循環(huán)前要判斷的條件,一旦條件不滿足馏颂,循環(huán)將結(jié)束示血。
- increment用來(lái)對(duì)計(jì)數(shù)器進(jìn)行更新,它在每次循環(huán)結(jié)束后執(zhí)行救拉。
??下面的程序使用for循環(huán)打印出1~10:
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
??注意變量i的聲明位置难审。由于它是在初始化表達(dá)式中聲明的,因此它的范圍和生存周期僅在循環(huán)內(nèi)有效亿絮。一旦循環(huán)結(jié)束告喊,變量i將無(wú)法訪問(wèn)。
??for循環(huán)的三個(gè)表達(dá)式都是可選的派昧,任意一個(gè)都可以為空黔姜。下面的語(yǔ)句將會(huì)創(chuàng)建一個(gè)無(wú)限循環(huán):
for ( ; ; ) {
// your code goes here
}
??for循環(huán)還有一種用于迭代數(shù)組和集合的格式,稱為增強(qiáng)型for循環(huán)蒂萎。下面的程序使用增強(qiáng)型for循環(huán)來(lái)遍歷數(shù)組:
class EnhancedForDemo {
public static void main(String [] args){
int [] numbers =
{1,2,3,4,5,6,7,8,9,10};
for(int item:numbers){
System.out.println(“Count is:”+ item);
}
}
}
三.中斷控制流
1.break
??break語(yǔ)句用于結(jié)束當(dāng)前控制結(jié)構(gòu)秆吵,它有兩種形式,帶標(biāo)簽的break語(yǔ)句和不帶標(biāo)簽的break語(yǔ)句五慈。在之前的switch樣例中已經(jīng)見(jiàn)到了不帶標(biāo)簽的break語(yǔ)句纳寂。還可以使用不帶標(biāo)簽的break語(yǔ)句終止for主穗,while或do-while循環(huán),如下面的BreakDemo程序:
class BreakDemo {
public static void main(String[] args) {
int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 };
int searchfor = 12;
int i;
boolean foundIt = false;
for (i = 0; i < arrayOfInts.length; i++) {
if (arrayOfInts[i] == searchfor) {
foundIt = true;
break;
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at index " + i);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
??該程序的輸出是:
Found 12 at index 4
??不帶標(biāo)簽的break語(yǔ)句跳出最內(nèi)層的循環(huán)或分支結(jié)構(gòu)毙芜,但帶標(biāo)簽的break語(yǔ)句可以跳出標(biāo)簽對(duì)應(yīng)的那個(gè)結(jié)構(gòu)忽媒。例如:
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 } };
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}
??當(dāng)找到12時(shí),程序?qū)⑻鰏earch對(duì)應(yīng)的for循環(huán)腋粥。該程序的輸出是:
Found 12 at 1, 0
2.continue
??continue跳到循環(huán)體的末尾晦雨,并執(zhí)行循環(huán)條件的判斷。下面的程序統(tǒng)計(jì)字母p的出現(xiàn)次數(shù)隘冲。如果當(dāng)前字符不是p闹瞧,則continue語(yǔ)句將跳過(guò)循環(huán)的其余部分并繼續(xù)執(zhí)行下一次循環(huán)。如果是 “p”对嚼,計(jì)數(shù)器會(huì)加1:
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
if (searchMe.charAt(i) != 'p')
continue;
numPs++;
}
System.out.println("Found " + numPs + " p in the string.");
}
}
??該程序的輸出是:
Found 9 p in the string.
??和break一樣,continue也分為帶標(biāo)簽的continue語(yǔ)句和不帶標(biāo)簽的continue語(yǔ)句绳慎。帶標(biāo)簽的continue語(yǔ)句將會(huì)結(jié)束當(dāng)前的循環(huán)并開(kāi)始下一次標(biāo)簽對(duì)應(yīng)的循環(huán)纵竖。下面的程序使用帶標(biāo)簽的continue和break語(yǔ)句來(lái)判斷一個(gè)字符串是否包含另一個(gè)字符串:
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() - substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
??該程序的輸出是:
Found it
3.return
??最后一個(gè)可以中斷控制流的語(yǔ)句是return語(yǔ)句,它可以從當(dāng)前的方法中退出杏愤。return語(yǔ)句有兩種形式靡砌,使用返回值和不使用返回值。如果要返回一個(gè)值珊楼,只需要將值或表達(dá)式放在return關(guān)鍵字后面通殃。例如:
return ++count;
??返回值的數(shù)據(jù)類型必須與方法聲明的返回值的類型匹配。使用沒(méi)有返回值的return語(yǔ)句時(shí)厕宗,方法的返回值類型必須聲明為void画舌,例如:
return;