# 迴圈的跳離

{% hint style="info" %}
跳離敘述會增加除錯與閱讀的困難，不得已情況下才使用。
{% endhint %}

### **一、break 敘述**

可以強迫跳離迴圈。

```
for(初值設定; 判斷條件; 設增減量)
{
    敘述1;
    敘述2;
     ...
    break; //僅執行到此行
     ...
    敘述3; //此敘述不會被執行
}
     ...
```

```
public class ch05_9 {

	public static void main(String[] args) {
		int i;

		for (i=1; i<=10; i++)
		{
			if(i%3==0)
				break;
			System.out.println("i="+i);  //此行執行結果並無印出
		}
		System.out.println("當迴圈中斷,i="+i);

	}
```

OUTPUT：\
i=1\
i=2\
當迴圈中斷,i=3

### **二、continue 敘述**

可以強迫跳到迴圈開頭。

```
for(初值設定; 判斷條件; 設增減量)
{
    敘述1;
    敘述2;
     ...
    continue; //僅執行到此行
     ...
    敘述3; //此敘述不會被執行
}
     ...
```

#### 試比較 **break** 與 continue 執行結果：

```
public class ch05_10 {

	public static void main(String[] args) {
		int i;

		for (i=1; i<=10; i++)
		{
			if(i%3==0)
				continue;
			System.out.println("i="+i);
		}
		System.out.println("當迴圈中斷,i="+i);

	}
```

OUTPUT：\
i=1\
i=2\
i=4\
i=5\
i=7\
i=8\
i=10\
當迴圈中斷,i=11

#### 三、switch敘述

```
switch(運算式)
{
   case 選擇值1:
        敘述主體1;
        break;
   case 選擇值2:
        敘述主體2;
        break;
         ...
   case 選擇值n:
        敘述主體n;
        break;
   default:     //若上述case 皆不適合，則會執行default的敘述
        敘述主體;
}
```

{% hint style="info" %}
選擇值可為 字元、字串或是整數

如果沒有加上break，則會一直執行到switch 敘述的尾端。
{% endhint %}

![](https://2439647256-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4NDwp0sFRvD07cdujE%2F-M4gm0VSFgmeVSv2xCXL%2F-M4gn7WjHV-AnMpl76iP%2Fimage.png?alt=media\&token=ee6a2022-43ed-4864-b7b9-077e210d5b03)

```
import java.util.Scanner;
public class ch05_11 {

	public static void main(String[] args) {
		Scanner scn=new Scanner (System.in);
		int a=50,b=20;

		System.out.print("a="+a+", b="+b+", 請輸入運算符號: ");
		char oper=scn.next().charAt(0); //取得第一個字元

		switch (oper)
		{
		case '+':
			System.out.println(a+"+"+b+"="+(a+b));
			break;
		case '-':
			System.out.println(a+"-"+b+"="+(a-b));
			break;
		case '*':
			System.out.println(a+"*"+b+"="+(a*b));
			break;
		case '/':
			System.out.println(a+"/"+b+"="+(a/b));
			break;
		default:
			System.out.println("不清楚此運算符號");
		}

	}
```

OUTPUT：\
a=50, b=20, 請輸入運算符號: +  // 試著輸入其他運算符號\
50+20=70
