二维数组
顾名思义,二维数组有二维的值,常视为有行和列构成的表。
1 public class TwoDArray
2 {
3 //-----------------------------------------------------------------
4 // 创建一个2D整数数组,填充它越来越多整数值,然后打印出来。
5 //-----------------------------------------------------------------
6 public static void main(String[] args)
7 {
8 int[][] table = new int[5][10];
9
10 // 使用值加载表
11 for (int row=0; row < table.length; row++)
12 for (int col=0; col < table[row].length; col++)
13 table[row][col] = row * 10 + col;
14
15 // 打印表格
16 for (int row=0; row < table.length; row++)
17 {
18 for (int col=0; col < table[row].length; col++)
19 System.out.print (table[row][col] + "\t");
20 System.out.println();
21 }
22 }
23 }
TwoDArray程序实例化了一个整形二维数组。与一维数组一样,二维数组每个维的大小再创建时就指,并且每个维的大小可以不同。
import java.text.DecimalFormat;
public class SodaSurvey
{
//-----------------------------------------------------------------
// 确定并打印每行和每行的平均值调查分数的列。
//-----------------------------------------------------------------
public static void main(String[] args)
{
int[][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4},
{2, 4, 3, 4, 3, 3, 2, 1, 2, 2},
{3, 5, 4, 5, 5, 3, 2, 5, 5, 5},
{1, 1, 1, 3, 1, 2, 1, 3, 2, 4} };
final int SODAS = scores.length;
final int PEOPLE = scores[0].length;
int[] sodaSum = new int[SODAS];
int[] personSum = new int[PEOPLE];
for (int soda=0; soda < SODAS; soda++)
for (int person=0; person < PEOPLE; person++)
{
sodaSum[soda] += scores[soda][person];
personSum[person] += scores[soda][person];
}
DecimalFormat fmt = new DecimalFormat("0.#");
System.out.println("Averages:\n");
for (int soda=0; soda < SODAS; soda++)
System.out.println("Soda #" + (soda+1) + ": " +
fmt.format((float)sodaSum[soda]/PEOPLE));
System.out.println();
for (int person=0; person < PEOPLE; person++)
System.out.println("Person #" + (person+1) + ": " +
fmt.format((float)personSum[person]/SODAS));
}
}
SodaSurvey程序使用了初始值表实例化二维数组。
多维数组
数组可以有一维、二维、三维甚至多维数组。多于一维的数组称为多维数组。
三维数组具有高、宽、深的概念,或者说行、列、层的概念。