一。break
1. break語句形式: break;
2. break語句功能:
A. switch語句中,break語句會終止其後語句的執行,退出switch語句。
B. 使一個循環立即結束,也就是說在循環中遇到break語句時,循環立即終止,
程序轉到循環體後的第一個語句去繼續執行。
3. 注:
A. break語句在循環中使用時,總是與if一起使用,當條件滿足(或不滿足)
時,負責退出循環。
B. 如果循環體中使用switch語句,而break出現在switch語句中,則它只用
於結束switch,而不影響循環。
C. break語句只能結束包含它的最內層循環,而不能跳了多重循環。
4. 例: break語句的執行只能從while循環中退出,繼續執行for循環的其它語句
而不是退出外層循環。
for()
{
:
:
while()
{
:
:
if() break;
:
:
}
:
:
}
二。continue
1.continue語句形式: continue;
2.continue語句功能: 它只能出現在循環體中,其功能是立即結束本次循環,
即遇到continue語句時,不執行循環體中continue後的語句,立即轉去判斷循環條件是否成立。
3.Continue與break語句的區別: continue只是結束本次循環,而不是終止整個循
環語句的執行,break則是終止整個循環語句的
執行,轉到循環語句後的下一條語句去執行。
程序表達式及流程圖如下:
(1.) while(表達式1) (2.)while(表達式1)
{ {
: :
If(表達式2) break; if(表達式2) continue;
: :
} }
三.goto
1.goto語句形式:goto語句是無條件轉向語句,其一般形式爲:
goto 語句標號;
2.功能:goto語句往往用來從多重循環中跳出。它在解決一些特定問題時很方便,但由於goto語句難於控制,儘量少用。
3.例:
IN:
For()
{
:
:
Goto IN;
}
四.Return
1.return語句形式: return (返回值);
2.功能:return可以返回一個函數的值,並且跳出這個函數;
Void doSomething(){
do whatever is required by this method …
return;
只要遇到return語句,程序就在那一行代碼停止執行,執行控制將立刻返回到調用該程序的代碼處。
對於返回值類型爲void的程序,return關鍵字單獨作爲完整的語句使用:
void doSomething(){
int x=3;
int y=4;
int x=x+y;
}
和
void doSomething(){
int x=3;
int y=4;
int x=x+y;
return;
}
return 0; //returning a constant integer value
return x; //returning the value of x(assuming that x has previously been declared to be an int)
return x+y; //returning the value of the expression”x+y”(here,we`re assuming that “x+y” evaluates to an int value)
return false; //returning a Boolean constant value
return outcome; //returning the value of variable outcome (assuming that outcome has previously been declared to be of type Boolean)
boolean isHonorsStudent(){
if(gpa>=3.5) return true; //first return statement
else return false; //second return statement
}
使用局部boolean型變量result來重寫這個程序,該變量捕獲最終返回的true/false結果。在程序最末尾用一條return語句返回result變量的值:
boolean isHonorsStudent(){
boolean result = false;
if(gpa>=3.5) result = true;
else result = false;
return result;
}
如上述代碼所示,由於已經給result變量賦予初值false,因此在else子句中明確地給它賦值false是不必要的,可以像下面這樣簡化isHornorsStudent程序:
boolean isHonorsStudent(){
boolean result = false;
if(gpa>=3.5) result = true;
return result;
function cs(n){
if(n==1) { retrun 1; }
if(n==2) { return; }
else { }
}
說明: 當參數爲1時函數返回值爲1並且跳出函數,
當參數爲2時函數返回值爲空並且跳出函數,
當函數爲其他值時繼續執行函數下面的語句,直到遇到下個return或則全部執行完語句在跳出函數