Design and implement a Java program for programming exercise
Solution
ColumnSorting.java
public class ColumnSorting {
public static void main(String[] args) {
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.println(\"Enter a 3-by-3 matrix row by row: \");
String firstRow = in.nextLine();
String firstRowValues[] = firstRow.split(\"\\\\s+\");
String secondRow = in.nextLine();
String secondRowValues[] = secondRow.split(\"\\\\s+\");
String thirdRow = in.nextLine();
String thirdRowValues[] = thirdRow.split(\"\\\\s+\");
double a[][] = new double[3][3];
for(int i=0; i<a.length; i++){
for(int j=0; j<a[i].length; j++){
if(i==0){
a[i][j] = Double.parseDouble(firstRowValues[j]);
}
else if(i==1){
a[i][j] = Double.parseDouble(secondRowValues[j]);
}
else if(i==2){
a[i][j] = Double.parseDouble(thirdRowValues[j]);
}
}
}
System.out.println(\"The column-sorted array is \");
double d[][] = sortColumns(a);
String s = \"\";
for(int i=0; i<d.length; i++){
for(int j=0; j<d[i].length; j++){
s = s + d[i][j] + \" \";
}
s = s + \"\ \";
}
System.out.println(s);
}
public static double[][] sortColumns(double[][] m) {
for(int i=0; i<m.length; i++){
double temp = 0;
for(int j=0; j<m[i].length-1; j++){
if(m[j][i] > m[j+1][i]){
temp = m[j][i];
m[j][i] = m[j+1][i];
m[j+1][i] = temp;
}
}
}
return m;
}
}
Output:
Enter a 3-by-3 matrix row by row:
0.15 0.875 0.375
0.55 0.005 0.225
0.30 0.12 0.4
The column-sorted array is
0.15 0.005 0.225
0.3 0.12 0.375
0.55 0.875 0.4

