We use 2D array to implement the matrices in java. Below is the example which shows how to take matrix data from the user and display them.
package testjava.arrays;
import java.util.Scanner;
public class CreateMatrix
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Number Of Rows");
int row = sc.nextInt();
System.out.println("Enter The Number Of Columns");
int cols = sc.nextInt();
//defining 2D array to hold matrix data
int[][] matrix = new int[row][cols];
System.out.println("Enter Matrix Data");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
matrix[i][j] = sc.nextInt();
}
}
System.out.println("Your Matrix is : ");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < cols; j++)
{
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
}
Output
Enter The Number Of Rows
3
Enter The Number Of Columns
3
Enter Matrix Data
1
2
3
4
5
6
7
8
9
Your Matrix is :
1 2 3
4 5 6
7 8 9