# 迴圈的跳離

{% 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 %}

![](/files/-M4gn7WjHV-AnMpl76iP)

```
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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-05/java-05-3.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
