To print the elements of a matrix in Java, you can use a loop to iterate over the rows and columns of the matrix and print the values of the elements.
Here is an example of how you can print the elements of a matrix in Java:
public class MatrixPrinter { public static void main(String[] args) { int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }
In this example, the main
method defines a 2D integer array with 3 rows and 3 columns and uses a nested loop to iterate over the rows and columns of the matrix. The outer loop iterates over the rows of the matrix, and the inner loop iterates over the columns of each row.
The inner loop prints the value of the element at the current row and column, and the outer loop prints a new line after the inner loop finishes iterating over all the columns of the current row.
This code will print the following output:
1 2 3 4 5 6 7 8 9
Keep in mind that this is just one way to print the elements of a matrix in Java. You can use different techniques and data structures to achieve the same result, such as using a stream or a StringBuilder
to build the output string.