O que é um array Matrix / 2D em Java?
“Uma matriz é uma coleção de números arranjados em um número fixo de linhas e colunas.” Normalmente são números reais. Em geral, as matrizes podem conter números complexos, mas, para simplificar, usaremos apenas números inteiros aqui. Vamos dar uma olhada em como é uma matriz. Aqui está um exemplo de uma matriz com 4 linhas e 4 colunas.Declarar e inicializar uma matriz 2D
Aqui estão algumas maneiras diferentes de declarar apenas o tamanho da matriz ou inicializá-la sem mencionar o tamanho.
public class Matrices {
public static void main(String[] args) {
// declare & initialize 2D arrays for int and string
int[][] matrix1 = new int[2][2];
int matrix2[][] = new int[2][3];
//the size of matrix3 will be 4x4
int[][] matrix3 = { { 3, 2, 1, 7 },
{ 9, 11, 5, 4 },
{ 6, 0, 13, 17 },
{ 7, 21, 14, 15 } };
String[][] matrix4 = new String[2][2];
//the size of matrix5 will be 2x3
// 3 cols because at max there are 3 columns
String[][] matrix5 = { { "a", "lion", "meo" },
{ "jaguar", "hunt" } };
}
}
Travessia de Array 2D
Todos nós sabemos como percorrer arrays regulares em Java. Para arrays 2D também não é difícil. Normalmente usamos loops 'for' aninhados para isso. Alguns iniciantes podem pensar nisso como um conceito estranho, mas assim que você se aprofundar nele, poderá implementá-lo com alguma prática. Dê uma olhada no trecho a seguir. Ele exibe apenas o número de colunas correspondentes a cada linha para sua compreensão completa.
public class MatrixTraversal {
public static void main(String[] args) {
int[][] matrix = new int[4][4];
for (int i = 0; i < matrix.length; i++)
{
// length returns number of rows
System.out.print("row " + i + " : ");
for (int j = 0; j < matrix[i].length; j++)
{
// here length returns # of columns corresponding to current row
System.out.print("col " + j + " ");
}
System.out.println();
}
}
}
Saída
carr 0 : col 0 col 1 col 2 col 3 carr 1 : col 0 col 1 col 2 col 3 carr 2 : col 0 col 1 col 2 col 3 carr 3 : col 0 col 1 col 2 col 3
Como imprimir uma matriz 2D em Java?
Depois que você estiver familiarizado com a travessia de Array 2D, vamos ver algumas maneiras de imprimir Arrays 2D em Java.Usando o loop “for” aninhado
Esta é a maneira mais básica de imprimir a matriz em Java.
public class MatrixTraversal {
public static void printMatrix(int matrix[][])
{
for (int i = 0; i < matrix.length; i++)
{
// length returns number of rows
for (int j = 0; j < matrix[i].length; j++)
{
// here length returns number of columns corresponding to current row
// using tabs for equal spaces, looks better aligned
// matrix[i][j] will return each element placed at row ‘i',column 'j'
System.out.print( matrix[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = { { 3, 2, 1, 7 },
{ 9, 11, 5, 4 },
{ 6, 0, 13, 17 },
{ 7, 21, 14, 15 } };
printMatrix(matrix);
}
}
Saída
3 2 1 7 9 11 5 4 6 0 13 17 7 21 14 15
Usando o loop “for-each”
Aqui está outra maneira de imprimir matrizes 2D em Java usando “ loop foreach ”. Este é um tipo especial de loop fornecido pelo Java, onde o int[]row irá percorrer cada linha da matriz. Considerando que, a variável “elemento” conterá cada elemento colocado no índice da coluna através da linha.
public class MatrixTraversal {
public static void printMatrix(int matrix[][]){
for (int [] row : matrix)
{
// traverses through number of rows
for (int element : row)
{
// 'element' has current element of row index
System.out.print( element + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] matrix = { { 3, 2, 1, 7 },
{ 9, 11, 5, 4 },
{ 6, 0, 13, 17 },
{ 7, 21, 14, 15 } };
printMatrix(matrix);
}
}
Saída
3 2 1 7 9 11 5 4 6 0 13 17 7 21 14 15
Usando o método “Arays.toString()”
Arrays.toString() método em Java, converte cada parâmetro passado para ele como um único array e usa seu método embutido para imprimi-lo. Criamos um array fictício String 2D para brincar. O mesmo método também funciona para arrays inteiros. Nós encorajamos você a praticá-lo para o seu exercício.
import java.util.Arrays;
public class MatrixTraversal {
public static void printMatrix(String matrix[][]){
for (String[] row : matrix) {
// convert each row to a String before printing
System.out.println(Arrays.toString(row));
}
}
public static void main(String[] args) {
String [][] matrix = { { "Hi, I am Karen" },
{ "I'm new to Java"},
{ "I love swimming" },
{ "sometimes I play keyboard"} };
printMatrix(matrix);
}
}
Saída
[Oi, eu sou a Karen] [Sou nova em Java] [Adoro nadar] [às vezes toco teclado]
GO TO FULL VERSION