二维数组的定义和使用

来源:互联网 发布:nginx保持会话 编辑:程序博客网 时间:2024/04/29 11:11


和一维数组类似。

我们使用二维数组,

也可以使用动态声明和静态声明两种方式。
动态声明,例如:
 int a[][];                              //声明数组
a=new int[行][列];            //数组实例化,初始化
或者一步到位:
int a[][]=new int[行][列];
包括一维数据,也可以在动态分配时,这样一步到位。
之后我们可以给我们的二维数组赋值,打印出来看一看

使用代码如下:
 int socre[][]=new int[5][5];
  socre[0][0]=2;//字符串赋值,不用int socre[][]形式
  socre[2][1]=6;
 
 for (int i = 0; i < socre.length; i++) {
for (int j = 0; j < socre[i].length; j++) {
System.out.print(socre[i][j]+"  ");
}System.out.println();
}

静态声明,我们要使用到大括号。
例如:
int a={{2,7},{3,7,8}{2,2}{7,5,6,4}};
大括号里面的每个括号,按顺序代表一行的内容,用逗号隔开

然后可以打印出来看看,使用代码如下:
int socre[][]={{3,1},{6,6,6},{5,66,77,88}};//都好隔开,外面仍要接顿号
for (int i = 0; i < socre.length; i++) {
for (int j = 0; j < socre[i].length; j++) {
System.out.print(socre[i][j]+" ");
}
System.out.println();
}
}


0 0
原创粉丝点击