matrix print java code example

Example 1: how to print a 2d array in java

for (int row = 0; row < arr.length; row++)//Cycles through rows
{
  for (int col = 0; col < arr[row].length; col++)//Cycles through columns
  {
    System.out.printf("%5d", arr[row][col]); //change the %5d to however much space you want
  }
  System.out.println(); //Makes a new row
}
//This allows you to print the array as matrix

Example 2: Java program to print 3x3 matrix

// Java program to print 3x3 matrix
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JavaPrint3x3Matrix
{
   public static void main(String[] args) throws IOException 
   {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      int[][] inputNumber = new int[3][3];
      int a, b;
      String strMatrix;
      System.out.println("Please enter elements to print 3x3 matrix: ");
      for(a = 0; a <= 2; a++)
      {
         for(b = 0; b <= 2; b++)
         {
            strMatrix = br.readLine();
            inputNumber[a][b] = Integer.parseInt(strMatrix);
         }
      }
      System.out.println("Elements in 3x3 matrix are: ");
      System.out.println("");
      for(a = 0; a <= 2; a++)
      {
         for(b = 0; b <= 2; b++)
         {
            System.out.print(inputNumber[a][b] + "\t");
         }
         System.out.println();
      }
   }
}

Example 3: print 2d array in java

int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));

Tags:

Java Example