[Java] 多维数组

类似于一维数组,二维数组声明定义初始化示例:

int[][] arr = int[5][5];

然后可以对数组进行赋值。
不同于C++,Java存在不规则数组(ragged arrays),即每行的列数可以不等。

int[][] triangleArray = {
    {1, 2, 3, 4, 5},
    {2, 3, 4, 5},
    {3, 4, 5},
    {4, 5},
    {5}
};

如果创建新数组, 使用语法new int[5][] ,必须指定第一个索引,语法 new int[][]是错误的。

例子:

import java.util.Scanner;
import java.io.*;
public class PassTwoDimensionalArray {   
    public static void main(String[] args) {
        int[][] m = getArray(); // Get an array
        // Display sum of elements
        System.out.println("\nSum of all elements is " + sum(m));                
    }            
    public static int[][] getArray() {
        Scanner input = new Scanner(System.in);
        // Enter array values
        int[][] m = new int[3][4];
        System.out.println("Enter " + m.length + " rows and " 
                + m[0].length + " columns: ");
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m[i].length; j++)
                m[i][j] = input.nextInt();
            return m;       
    }
    public static int sum(int[][] m) {  
        int result = 0;
        for (int i = 0; i < m.length; i++) 
            for (int j = 0; j < m[i].length; j++)
                result += m[i][j];        
        return result;
    }      
}

运行结果:

Enter 3 rows and 4 columns: 
1 2 3 4
0 0 0 0
5 6 7 8
Sum of all elements is 36

以2维数组为例,数组的长度例如上例中的mm.length, 为数组的行数,m[0].length为第1行的列数。


[1] Introduction to Java Programming chapter 8 multidimensional arrays

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值