# 函數與引數

> 函數可以簡化主程式的結構，節省撰寫相同的程式碼
>
> method 譯為「函數」，亦有作者譯為「方法」

### 一、函數設定

```
public static 傳回值型態 函數名稱 (型態 引數1, 型態 引數2,...)
{
   程式敘述;         // 函數主體
   return 運算式;    // 函數主體
}
```

若不需傳遞引數到函數中，小括號內可省略；若無回傳值，則可省略return。

```
public static 傳回值型態 函數名稱 ()
{
   程式敘述;         // 函數主體
}
```

```
public class ch07_1 {

	public static void main(String[] args)
	{
		star();    //呼叫star函數
		System.out.println("使用函數印星星");
		star();    //呼叫star函數

	}

	public static void star()  //star函數
	{
		for(int i=0; i<20; i++)
			System.out.print("*");
		System.out.print("\n");
	}
```

OUTPUT：\
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\
使用函數印星星\
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*

### 二、引數資料型態

> 若有回傳值，必須指定回傳的資料型態；若有引數要回傳到函數內，括號內需填上其資料型態。

```
public class ch07_2 {

	public static void main(String[] args)
	{
		int i;
		i=star(9);
		System.out.println(i+"個星星，使用函數印出");
	}

	public static int star(int n)  //注意資料型態
	{
		for(int i=0; i<2*n; i++)
			System.out.print("*");
		System.out.print("\n");
		return 2*n;
	}
```

OUTPUT：\
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\
18個星星，使用函數印出

### 三、傳遞多個引數

> 傳遞一個以上的引數，只要在括號內填上即可

```
public class ch07_3 {

	public static void main(String[] args) {
		double num;
		num=show(8,4);
		System.out.println("長度= "+num);
	}

	public static double show(int m, int n)
	{
		return Math.sqrt(m*m+n*n);
	}
```

OUTPUT：\
長度= 8.94427190999916

{% hint style="info" %}
sqrt(n) 的用法是將引數n開根號
{% endhint %}

### 四、函數傳值（pass by value）

> 所有基本資料型態變數，傳遞到函數的方法都是「傳值（pass by value）」

```
public class ch07_4 {

	public static void main(String[] args) {
		int num=5;
		add10(num);
		System.out.println("在主程式 main(), num= "+num);
	}
	public static void add10(int value)
	{
		value+=10;
		System.out.println("在函數add10(), 值為 "+value);
	}
```

OUTPUT：\
在函數add10(), 值為 15\
在主程式 main(), num= 5

{% hint style="info" %}
若是傳遞陣列，或由類別建立的物件時，必須以「傳參照（pass by reference）」方式
{% 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-07/java-07-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.
