C++
1、 採用goto語句
goto語句雖然一直被大家所詬病,說破壞了代碼的結構化特性,但是它也有自己的好處。
goto語句肯定不推薦大量使用,但是對於跳出多重循環還是特定方便,邏輯也比較清晰。
#include <iostream>
using namespace std;
int main(){
for(int i=1;i<10;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3)
goto mark;
cout<<i<<" "<<j<<endl;
}
}
mark:
return 0;
}
結果:
2、 循環內多增加一個判斷條件
對於退出循環不是特別迫切的,允許執行完本輪循環的,建議可以採用這種方式。
#include <iostream>
using namespace std;
int main(){
bool flag=true;
for(int i=1;i<10 && flag;i++){
for(int j=0;j<5 && flag;j++){
if(i==2 && j==3)
flag=false;
cout<<i<<" "<<j<<endl;
}
}
mark:
return 0;
}
結果:
我們可以看到這裏比使用goto多了一個2 3
,因爲我們不是立刻退出循環的,所以使用goto還是使用這個可以根據實際情況選擇。
Java補充
1、break/continue tag
Java和C++大部分是類似的,但是Java是廢棄了goto的,但是它提供了另外一個類似於goto的方法;
public class test2 {
public static void main(String[] args){
flag:for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3){
break flag;
}
System.out.println(i+" "+j);
}
}
System.out.print("循環退出了");
}
}
結果:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
循環退出了
Process finished with exit code 0
2、採用異常處理的方式
java的異常處理機制允許碰到異常直接跳到catch,不執行後面try語句,利用這個特性:
public class test2 {
public static void main(String[] args){
try{
flag:for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3){
throw new Exception();
}
System.out.println(i+" "+j);
}
}
}catch (Exception e){
System.out.print("循環退出了");
}
}
}
結果:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
循環退出了
Process finished with exit code 0