Create matrix with user input in java

Let’s learn to create matrix with user input in java.

Create matrix with user input in java

In the below java program first user enters number of rows and columns as input using nextInt() method of Scanner class.

This input is stored in two integer variables ‘row’ and ‘col’.

In the next step two dimensional array is defined with ‘row’ and ‘col’ values.

Then using fillingMatrix() and printingMatrix() methods matrix is filled with user input and finally printed on the console.

Here’s the java program on creating matrix with user input.

import java.util.Scanner;
public class MatrixUserInput
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number of matrix rows : ");
      int row = sc.nextInt();
      System.out.println("Please enter number of matrix columns : ");
      int col = sc.nextInt();
      // defining two dimensional array java
      int[][] numbers = new int[row][col];
      // filling java matrix
      fillingMatrix(sc, numbers, row, col);
      // printing 2d array in matrix form in java
      printingMatrix(numbers, row, col);
   }
   public static void fillingMatrix(Scanner scan, int num[][], int rows, int columns)
   {
      System.out.println("Please enter elements in matrix : ");
      for(int a = 0; a < rows; a++)
      {
         for(int b = 0; b < columns; b++)
         {
            num[a][b] = scan.nextInt();
         }
      }
   }
   public static void printingMatrix(int num[][], int rows, int columns)
   {
      System.out.println("Printing matrix : ");
      for(int a = 0; a < rows; a++)
      {
         for(int b = 0; b < columns; b++)
         {
            System.out.print(num[a][b] + "\t");
         }
         System.out.println();
      }
   }
}


Output:

Please enter number of matrix rows :
3
Please enter number of matrix columns :
3
Please enter elements in matrix :
10
20
30
40
50
60
70
80
90
Printing matrix :
10 20 30
40 50 60
70 80 90


Also read – Merge sort java