# 一維陣列

> 陣列可以存放相同的資料型態資料，並利用索引值存取其內容。

### 一、宣告方式

必須先宣告陣列後配置記憶體位置給陣列。

```
資料型態 陣列名稱[];
陣列名稱＝new 資料型態[數量];
```

```
int score[];   //宣告整數陣列score
score=new int[5]; //使陣列score 可存放5個整數的記憶體空間
```

#### 較簡潔的方式：

```
資料型態 陣列名稱[]＝new 資料型態[數量];
```

&#x20;`int score[ ];` 還有另外的宣告方式：

```
int[] score;
int  []score;
```

### 二、取得陣列長度 length

```
public class ch06_1 {

	public static void main(String[] args) {
		int i;
		int a[];
		a=new int[3];
		a[0]=9;
		a[1]=6;

		for(i=0; i<a.length; i++)
			System.out.print("a["+i+"]="+a[i]+",\t");
		System.out.println("字串長度："+a.length);


	}
```

OUTPUT：\
a\[0]=9, a\[1]=6, a\[2]=0, 字串長度：3

### 三、陣列設初值

```
陣列名稱[]＝{1,2,3};
```

```
public class ch06_2 {

	public static void main(String[] args) {
		int i;
		int a[]={10,20,30}; //自動依序指定給第0,第1,第2個元素


		for(i=0; i<a.length; i++)
			System.out.println("a["+i+"]="+a[i]);
		System.out.println("字串長度："+a.length);

	}
```

OUTPUT：\
a\[0]=10\
a\[1]=20\
a\[2]=30\
字串長度：3

### 四、尋找陣列中最大最小值

```
public class ch06_3 {

	public static void main(String[] args) {
		int i,min,max;
		int a[]={22,15,89,74,3};  //給定陣列初值
		min=max=a[0];   //先將min,max 分別設為陣列第一個元素
		for(i=0; i<a.length; i++)
                {
                    System.out.print(a[i]+" "); //印出陣列
                    if(a[i]>max) //如果第i個元素 比max大(一開始將max設為第0個元素)
			max=a[i]; // 則將a[i]設為max
		    if(a[i]<min)
			min=a[i];  //min 同理
		}
		System.out.println("\nmax= "+max);
		System.out.println("min= "+min);

	}
```

OUTPUT：\
22 15 89 74 3\
max= 89\
min= 3


---

# 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-06/java-06-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.
