Write a java program called ColumnSorting that asks the user to enter a 3-by-3 a
ID: 3762572 • Letter: W
Question
Write a java program called ColumnSorting that asks the user to enter a 3-by-3 array of doubles, entering the values one row at a time. The program then displays the array with each column being separately sorted, meaning that each column continues to have the same numbers in it as were inputted, but those numbers are printed out in each column in sorted order from smallest to largest. Your main() method must call the following method to accomplish this task:
Notice that this method returns a new array, and the original array should remain unchanged.
Design the main() method of your program such that it allows the user to re-run the program with different inputs (i.e., use a loop structure).
Here is a sample input and output:
Explanation / Answer
import java.util.Arrays;
import java.util.Scanner;
public class ColumnSorting {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a 3-by-3 matrix row by row:");
double[][] inArray = new double[3][3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < inArray.length; i++) {
for (int j = 0; j < inArray[i].length; j++) {
inArray[i][j] = scanner.nextDouble();
}
}
double sortedArray[][] = sortColumns(inArray);
System.out.println("After sorting");
for (int i = 0; i < sortedArray.length; i++) {
for (int j = 0; j < sortedArray[i].length; j++) {
System.out.print(sortedArray[i][j] + " ");
}
System.out.println();
}
}
public static double[][] sortColumns(double[][] inArray) {
double inArray1[][] = new double[3][3];
for (int i = 0; i < inArray.length; i++) {
double tempArr[] = new double[inArray.length];
for (int j = 0; j < inArray[i].length; j++) {
tempArr[j] = inArray[j][i];
}
Arrays.sort(tempArr);
for (int j = 0; j < inArray[i].length; j++) {
inArray1[j][i] = tempArr[j];
}
}
// System.out.println();
return inArray1;
}
}
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
After Sorting
0.15 0.0050 0.225
0.3 0.12 0.375
0.55 0.875 0.4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.