编写一个程序,提示用户输入一个双值的nxn矩阵,并显示一个新的矩阵,其中对初始矩阵的列进行排序。您可以使用任何排序算法来解决这个问题;请在代码头中指定使用的排序算法的名称。程序必须实现排序算法;不能使用Array类中提供的排序方法。应该将排序实现为一个方法,在该方法中返回一个新数组,并且原始数组完好无损:
public static double[][] sortCol(double[][] a)程序还应该实现一种方法,将初始矩阵和结果矩阵打印给用户。打印出来的格式应该很好。下面是一个示例运行:
What is the dimension of matrix? 3
Enter a 3x3 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这就是我所拥有的。我相信它几乎是完美的。我认为使用的排序方法将对列进行排序,但也可能是对行进行排序。但是当我运行这个程序的时候我得到了这个..。
线程"main“java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.next at Hmwk3_jrgluck.main(Hmwk3_jrgluck.java:16)中的异常
任何想法/帮助..。
import java.util.Scanner;
public class sdfjasdf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("What is the dimension of your matrix?");
int matrixdim = input.nextInt();
double[][] matrix = new double[matrixdim][matrixdim];
System.out.println("Enter " + matrixdim + " rows, and " + matrixdim
+ " columns.");
Scanner input1 = new Scanner(System.in);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix.length; column++)
matrix[row][column] = input1.nextDouble();
}
System.out.println(sortCol(matrix));
}
public static double sortCol(double[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
double currentMin = matrix[i][0];
int currentMinIndex = i;
for (int j = i; j < matrix.length; j++) {
if (currentMin > matrix[j][0]
|| (currentMin == matrix[j][0] && matrix[currentMinIndex][1] > matrix[j][1])) {
currentMin = matrix[j][0];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
double temp0 = matrix[currentMinIndex][0];
double temp1 = matrix[currentMinIndex][1];
matrix[currentMinIndex][0] = matrix[i][0];
matrix[currentMinIndex][1] = matrix[i][1];
matrix[i][0] = temp0;
matrix[i][1] = temp1;
}
}
return sortCol(matrix);
}
}发布于 2013-06-14 14:05:09
我怀疑您的地区可能需要逗号而不是浮点数格式的点。尝试将数据更改为
0,15 0,875 0,375
0,55 0,005 0,225
0,30 0,12 0,4如果这是真的,但您更愿意(或必须)使用点而不是逗号,则可以通过调用
input.useLocale(new Locale("en", "US"));或在创建Scanner对象之前更改全局区域设置
Locale.setDefault(new Locale("en", "US"));而且返回类型的sortCol应该是以太。
double[][],以防您想返回排序过的数组副本(而不更改原始副本)。在这种情况下,您需要首先使用create copy of original arrayvoid,如果您想对原始数组进行排序(您不必返回对您已经拥有的对象的引用,因为您使用它作为方法参数)现在您正试图通过再次调用double来返回sortCol(matrix),因此它将再次尝试返回sortCol(matrix) (以此类推),这将导致stack overflow。
https://stackoverflow.com/questions/17110209
复制相似问题