> For the complete documentation index, see [llms.txt](https://java.4-x.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://java.4-x.tw/java-06/java-06-2.md).

# 二維與多維陣列

### 一、二維陣列

二維陣列更方便處理較複雜的運算。

```
資料型態 陣列名稱[][];
陣列名稱＝new 資料型態[列的個數][行的個數];  //而列的個數一定要填
```

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

#### 較簡潔的方式：

```
資料型態 陣列名稱[][]＝new 資料型態[列個數][行個數]; //列的個數一定要填
```

int score \[2]\[4] 的圖表示意圖：

| <p>(0,0)<br>１５</p> | <p>(0,1)<br>２５</p> | <p>(0,2)<br>３０</p> | <p>(0,3)<br>１７</p> |
| ------------------ | ------------------ | ------------------ | ------------------ |
| <p>(1,0)<br>２２</p> | <p>(1,1)<br>５２</p> | <p>(1,2)<br>１０</p> | <p>(1,3)<br>８</p>  |

若要直接給陣列初值可以這麼做：（搭配以上圖表做示範）

```
int score[][]=
{   
  {15,25,30,17},
  {22,52,10,8}
};
```

### 二、取得二維陣列行數 length

> 陣列名稱.length&#x20;
>
> 陣列名稱\[列].length //可以取得陣列某列的個數

```
public class ch06_4 {

	public static void main(String[] args) {
		int i,j;
		int score[][]={{15,25,30,17},{22,52,10,8}};

		for(i=0; i<score.length; i++)
		{
		   for(j=0; j<score[i].length; j++) //這此運用到取得第i列的元素個數
		   {
		      System.out.println("score["+i+"]["+j+"]="+score[i][j]);
		   }
		}
		System.out.println("陣列行數："+score.length);
	}
```

OUTPUT：\
score\[0]\[0]=15\
score\[0]\[1]=25\
score\[0]\[2]=30\
score\[0]\[3]=17\
score\[1]\[0]=22\
score\[1]\[1]=52\
score\[1]\[2]=10\
score\[1]\[3]=8\
陣列行數：2

### 三、多維陣列

> 多維陣列如同一個立方體

#### 運用一維與二維的基礎，試撰寫從多維陣列中找出最大值與最小值：

```
public class ch06_5 {

	public static void main(String[] args) {
		int a[][][]={  //設定2x4x3的陣列
			     {
			        {15,85,36},
			        {30,14,37},
			        {47,23,96},
			        {19,39,51}
			      },
			      {
			        {22,16,51},
			        {97,30,12},
			        {68,77,26},
			         57,32,76}
			       }
			      };
		int i,j,k;
		int max=a[0][0][0],min=a[0][0][0];

		for(i=0; i<a.length; i++)
		  for(j=0; j<a[i].length; j++)
		    for(k=0; k<a[i][j].length; k++)
                     {
                        System.out.println("score["+i+"]["+j+"]["+k+"]="+a[i][j][k]);
                        if(max>a[i][j][k])
			 max=a[i][j][k];
			if(min<a[i][j][k])
			 min=a[i][j][k];
		      }
		System.out.println("max= "+max);
		System.out.println("min= "+min);

	}
```

![OUTPUT](/files/-M4gp_GRc9LDnlkA_RAq)
