Get all elements
Use the length property of the array directly to get the number of array elements in a one-dimensional array. In a two-dimensional array, you can directly use the length property to get the number of rows in the array. Adding length (such as array[0].length) after the specified index indicates how many elements the row has, that is, the number of columns.
If you want to get all the elements in a two-dimensional array, the simplest and most common way is to use the for statement. When outputting all one-dimensional arrays, we use a one-level for loop, while for two-dimensional arrays to output all of them, we use nested for loops (two-level for loops).
class test07
{
public static void main(String[] args)
{
double[][] class_score = {
{10.0,99,99},{100,98,97},{100,100,99.5},{99.5,99,98.5}};
System.out.println("第二行第二列的值:" + class_score[1][1]);
System.out.println("第四行第一列的值:" + class_score[3][0]);
//遍历二维数组
for(int i = 0; i < class_score.length; i++){
for(int j = 0; j < class_score[i].length; j++){
System.out.println("class_score[" + i + "][" + j + "] = " + class_score[i][j]);
}
}
}
}
Suppose there is a matrix with 5 rows and 5 columns. The matrix is arranged by numbers within 10 randomly generated by the program. The following uses a two-dimensional array to create the matrix, the code is as follows:
class test08
{
public static void main(String[] args)
{
//创建一个二维数组
int[][] matrix = new int[5][5];
//随机分配
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
matrix[i][j] = (int)(Math.random() * 10);
}
}
System.out.println("下面是程序生成的矩阵:");
//遍历二维数组并输出
for(int i = 0; i < matrix.length; i++){
for(int k = 0; k < matrix[i].length; k++){
System.out.print(matrix[i][k] + " ");
}
System.out.println();
}
}
}
foreach loop statement output
for(double[] row : class_score){
for(double val : row){
System.out.print(val + " ");
}
System.out.println();
}
To quickly print a list of data elements in a two-dimensional array, you can call:
System.out.println(Arrays.deepToString(arrayName));
import java.util.Arrays;
System.out.println(Arrays.deepToString(class_score));