# 選擇性敘述

### 一、程式的結構

* 循序性結構（sequence structure）：由上至下 （top to down）的敘述方式。
* 選擇性結構（selection structure）：先判斷條件是否成立，再決定執行哪些敘述。
* 重複性結構（iteration structure）：判斷條件是否成立，並決定程式段落的執行次數。

{% hint style="info" %}
三者的共通點為：只有一個進入點，也只有一個出口。
{% endhint %}

{% hint style="info" %}
選擇性結構包括 if、if-else、switch
{% endhint %}

### 二、if 敘述

i如果主體中只有一個敘述，則可以省略左右大括號。

當條件成立(true)，就會逐一執行大括號內的敘述。

```
if(判斷條件)
{
     敘述主體;
}
```

![](/files/-M4gjzPexWHHz56hD7sT)

### 三、if-else 敘述

當條件成立(true)，就會執行敘述主體；不成立時，則執行else 的敘述主體。以下為格式

```
 if(判斷條件)
{
     敘述主體A;
}
else
{
     敘述主體B;
}
```

![](/files/-M4gk5r9vwNrWLGcyZ-s)

```
public class ch05_1 {

	public static void main(String[] args) {
		int a=10;

		if (a%2==0)  // 如果可被2整除，判斷奇偶數
			System.out.println(a+" 為偶數");
		else
			System.out.println(a+" 為奇數");

	}
```

OUTPUT：\
10 為偶數

### 四、巢狀 if 敘述

if 敘述中又包含其它 if 敘述。以下為格式

```
if(判斷條件1)
{
  if(判斷條件2)
  {
     敘述主體;
  }
  ...
  其它敘述;
}
```

當判斷條件1為真，就會執行他敘述中的 判斷條件2；\
若判斷條件2也為真時，就會執行判斷條件2 的敘述主體。<br>

![](/files/-M4gkGbm0W9QQzNQVSrk)

```
public class ch05_2 { //使用 ch05_1 做延伸

	public static void main(String[] args) {
		int a=10;
		if(a>0)
		{
			if (a%2==0)  // 如果可被2整除，判斷奇偶數
				System.out.println(a+" 為大於0的偶數");
			else
				System.out.println(a+" 為大於0的奇數");
		}
	}
```

OUTPUT：\
10 為大於0的偶數

{% hint style="info" %}
過多的巢狀 if 反而會造成邏輯判斷的混淆，拖累執行的速度
{% endhint %}

### 五、條件運算子

進階用法，直接透過運算子可以代替if-else敘述

```
整數 ＝ 判斷條件 ？ 運算式1 ： 運算式2
```

```
public class ch05_3 {

	public static void main(String[] args) {
		int a=19,b=10,max;

		max=(a>b)?a:b;  // 當a>b時，max=a，否則 max=b

		System.out.println("a= "+a+", b= "+b);
		System.out.println(max+"為最大的數");

	}
```

OUTPUT：\
a= 19, b= 10\
19為最大的數

{% hint style="info" %}
使用條件運算子可以使程式碼較簡潔，執行速度也較有效率
{% endhint %}


---

# 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-1.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.
