How to Take 2D Array Input in Java - The Coding Shala

Home >> Java Programs >> Take 2D Array Input

 In this post, we are going to learn how to take 2D array/matrix input in Java.

How to Take 2D Array Input in Java

Write a Java program to take 2D array input from the user. Here we are going to take only an integer data type array. 

As we know, a 2D array has rows and columns so first take the number of rows and columns from user input and then create an array of that size. We are going to use the Scanner class to take the inputs.

Java Program: 

import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of rows");
        int n = sc.nextInt();
        System.out.println("Enter the number of columns");
        int m = sc.nextInt();

        // create n*m size 2d array/matrix
        int[][] matrix = new int[n][m];

        // take elements as input
        System.out.println("Enter the elements");
        for (int i=0; i<n; i++) {
            for (int j=0; j < m; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }

        // print the matrix
        System.out.println("2D array is: ");
        for (int i=0; i<n; i++) {
            for (int j=0; j < m; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output: 

Enter the number of rows
3
Enter the number of columns
3
Enter the elements
1
2
3
4
5
6
7
8
9
2D array is: 
1 2 3 
4 5 6 
7 8 9 


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala