How to Read a 2d Array in Java

Published by user on

Today we are going to learn how to read a 2d array in Java.

To construct a two-dimensional array, we want the number of rows, columns, and its elements. Finally, we display all the user input in a matrix format.

Program to read a 2d array in java

Let’s have a look at the program now.

import java.util.Scanner;

public class ReadTwoDimensionalDemo {
	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);

		int inputArr[][] = new int[5][5];

		System.out.println("Enter the number of rows : ");
		int noOfRows = scan.nextInt();
		System.out.println("Enter the number of columns : ");
		int noOfCols = scan.nextInt();

		int noOfElements = noOfRows * noOfCols;

		System.out.println("Please enter " + noOfElements + " elements nows.");

		// read array elements row wise.
		for (int i = 0; i < noOfRows; i++) {
			for (int j = 0; j < noOfRows; j++) {
				inputArr[i][j] = scan.nextInt();
			}
		}

		// close the scanner
		scan.close();
		System.out.println("The Input array is :");
		for (int i = 0; i < noOfRows; i++) {
			for (int j = 0; j < noOfRows; j++) {
				System.out.print(inputArr[i][j] + "\t");
			}
			System.out.println();
		}
	}
}

Output:

Enter the number of rows :
2
Enter the number of columns :
2
Please enter 4 elements nows.
6
8
3
7
The Input array is :
6 8
3 7

Program Explanation:

It accepts the number of rows and columns from the user, then it asks for the elements of the 2d array.

Each element is assigned to inputArr[i][j].

Finally, it displays the input in a matrix format.

It closes the scanner object to release the resource.

That’s all for reading a two-dimensional array. Please share this article if you find it useful.

Categories: Java