用Java打印二维数组或矩阵

先决条件: Java中的数组 , Java中的数组声明(单个和多维)

null

方法1(简单遍历)

我们可以使用mat计算矩阵mat[]中的行数。长为了找到第i行中的列数,我们使用mat[i]。长

JAVA

// Java program to print the elements of
// a 2 D array or matrix
import java.io.*;
class GFG {
public static void print2D( int mat[][])
{
// Loop through all rows
for ( int i = 0 ; i < mat.length; i++)
// Loop through all elements of current row
for ( int j = 0 ; j < mat[i].length; j++)
System.out.print(mat[i][j] + " " );
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}


输出

1 2 3 4 5 6 7 8 9 10 11 12 

方法2(使用 对于每个循环 )

这与上面的类似。这里我们使用for-each循环,而不是simple for循环。

JAVA

// Java program to print the elements of
// a 2 D array or matrix using for-each
import java.io.*;
class GFG {
public static void print2D( int mat[][])
{
// Loop through all rows
for ( int [] row : mat)
// Loop through all columns of current row
for ( int x : row)
System.out.print(x + " " );
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}


输出

1 2 3 4 5 6 7 8 9 10 11 12 

方法3(使用 数组。toString() )

数组。toString(世界其他地区) 转换将整行转换为字符串,然后将每行打印在单独的行中。

JAVA

// Java program to print the elements of
// a 2 D array or matrix using toString()
import java.io.*;
import java.util.*;
class GFG {
public static void print2D( int mat[][])
{
// Loop through all rows
for ( int [] row : mat)
// converting each row as string
// and then printing in a separate line
System.out.println(Arrays.toString(row));
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}


输出

[1, 2, 3, 4][5, 6, 7, 8][9, 10, 11, 12]

方法4(使用Arrays.deepToString()以矩阵样式打印)

数组。deepToString(int[])只需一步即可将2D数组转换为字符串。

JAVA

// Java program to print the elements of
// a 2 D array or matrix using deepToString()
import java.io.*;
import java.util.*;
class GFG {
public static void print2D( int mat[][])
{
System.out.println(Arrays.deepToString(mat));
}
public static void main(String args[])
throws IOException
{
int mat[][] = { { 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 } };
print2D(mat);
}
}


输出

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

本文由 尼基塔·蒂瓦里和洛夫什·东格尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享