Answer:
import java.io.*;
import java.util.Arrays;
class Main {
public static void main(String args[])
throws IOException{
// Set up keyboard input
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
// Prompt for dimensions MxN of the matrix
System.out.print("M = ");
int m = Integer.parseInt(br.readLine());
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
// Check if input is within bounds, exit if not
if(m <= 2 || m >= 10 || n <= 2 || n >= 10){
System.out.println("Matrix size out of range.");
return;
}
// Declare the matrix as two-dimensional int array
int a[][] = new int[m][n];
// Prompt for values of the matrix elements
System.out.println("Enter elements of matrix:");
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
a[i][j] = Integer.parseInt(br.readLine());
}
}
// Output the original matrix
System.out.println("Original Matrix:");
printMatrix(a);
// Sort each row
for(int i = 0; i < m; i++){
Arrays.sort(a[i]);
}
// Print sorted matrix
System.out.println("Matrix after sorting rows:");
printMatrix(a);
}
// Print the matrix elements separated by tabs
public static void printMatrix(int[][] a) {
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++)
System.out.print(a[i][j] + "\t");
System.out.println();
}
}
}
Step-by-step explanation:
I fixed the mistake in the original code and put comments in to describe each section. The mistake was that the entire matrix was sorted, while only the individual rows needed to be sorted. This even simplifies the program. I also factored out a printMatrix() method because it is used twice.