Given task is to read a matrix from the user. The size and number of elements of matrices are to be read from the keyboard.
// Java program to read a matrix from user import java.util.Scanner; public class MatrixFromUser { // Function to read matrix public static void readMatrixByUser() { int m, n, i, j; Scanner in = null; try { in = new Scanner(System.in); System.out.println("Enter the number " + "of rows of the matrix"); m = in.nextInt(); System.out.println("Enter the number " + "of columns of the matrix"); n = in.nextInt(); // Declare the matrix int first[][] = new int[m][n]; // Read the matrix values System.out.println("Enter the elements of the matrix"); for (i = 0; i < m; i++) for (j = 0; j < n; j++) first[i][j] = in.nextInt(); // Display the elements of the matrix System.out.println("Elements of the matrix are"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) System.out.print(first[i][j] + " "); System.out.println(); } } catch (Exception e) { } finally { in.close(); } } // Driver code public static void main(String[] args) { readMatrixByUser(); } } |
chevron_right
filter_none
Output:
Enter the number of rows of the matrix 2 Enter the number of columns of the matrix 2 Enter the elements of the matrix 1 2 3 4 Elements of the matrix are 1 2 3 4
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Program to multiply two Matrix by taking data from user
- Take Matrix input from user in Python
- Ways to read input from console in Java
- Image Processing in Java | Set 1 (Read and Write)
- Java program to read all mobile numbers present in given file
- How to make an ArrayList read only in Java
- How to Read and Print an Integer value in Java
- Reader read(char[]) method in Java with Examples
- Reader read(char[], int, int) method in Java with Examples
- Reader read(CharBuffer) method in Java with Examples
- Reader read() method in Java with Examples
- CharArrayReader read() method in Java with Examples
- CharArrayReader read(CharBuffer) method in Java with Examples
- CharArrayReader read(char[], int, int) method in Java with Examples
- CharArrayReader read(char[]) method in Java with Examples
- StringReader read(char[]) method in Java with Examples
- StringReader read(char[], int, int) method in Java with Examples
- StringReader read(CharBuffer) method in Java with Examples
- StringReader read() method in Java with Examples
- PushbackReader read(char, int, int) method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

