Create Matrix With User Input Using Java

  1. Home
  2. Blog
  3. Create Matrix With User Input Using Java

Create Matrix With User Input Using Java

Using 2D array to implement the matrices in java. Below example shows how to take matrix data from the user inputs and display them.

package com.ms.matrix;

import java.util.Scanner;

public class CreateMatrix {

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
        
        System.out.println("Enter The Number Of Matrix Rows");
         
        int matrixRow = scan.nextInt();
         
        System.out.println("Enter The Number Of Matrix Columns");
         
        int matrixCol = scan.nextInt();
         
        //defining 2D array to hold matrix data
        int[][] matrix = new int[matrixRow][matrixCol];

        // Enter Matrix Data
        enterMatrixData(scan, matrix, matrixRow, matrixCol);
        
        // Print Matrix Data
        printMatrix(matrix, matrixRow, matrixCol);
  }

  public static void enterMatrixData(Scanner scan, int[][] matrix, int matrixRow, int matrixCol){
     System.out.println("Enter Matrix Data");
          
          for (int i = 0; i < matrixRow; i++)
          {
              for (int j = 0; j < matrixCol; j++)
              {
                  matrix[i][j] = scan.nextInt();
              }
          }
  }
  
  public static void printMatrix(int[][] matrix, int matrixRow, int matrixCol){
    System.out.println("Your Matrix is : ");
        
        for (int i = 0; i < matrixRow; i++)
        {
            for (int j = 0; j < matrixCol; j++)
            {
                System.out.print(matrix[i][j]+"\t");
            }
             
            System.out.println();
        }
  }
}

Below is out of above program.

Enter The Number Of Matrix Rows
3
Enter The Number Of Matrix Columns
3
Enter Matrix Data
34
56
67
35
68
98
86
564
676
Your Matrix is : 
34	56	67	
35	68	98	
86	564	676

 

Let's Share

Comments (2)

  1. Consider a 2D matrix of numbers from 0 to 9 with variable width and height. Find the square submatrix with the highest sum of boundary elements.

    Input :

    Input width and height of matrix: 6 8

    Input Matrix with numbers from 0 to 9:

    2 0 6 1 2 5
    1 0 5 0 1 3
    3 0 1 2 4 1
    0 1 3 1 1 9
    4 1 0 8 5 2
    0 1 0 1 2 3
    6 5 3 1 0 2
    0 0 1 6 0 4

    Input maximum width of square submatrix (for square submatrix height and width are same) : 3

    Output :

    As sum of highlighted submatrix is maximum (calcute sum of boundary elements only 2,4,1,9,2,5,8,1),

    2 0 6 1 2 5
    1 0 5 0 1 3
    3 0 1 2 4 1
    0 1 3 1 1 9
    4 1 0 8 5 2
    0 1 0 1 2 3
    6 5 3 1 0 2
    0 0 1 6 0 4

    Output should be :

    2 4 1
    1 1 9
    8 5 2

Comments are closed.

Show Buttons
Hide Buttons