[英]java two dimensional array sorting
编写一个程序,提示用户输入一个双精度值的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
这就是我所拥有的。 我相信这几乎是完美的。 我认为我使用的排序方法将对列进行排序,但也可能对行进行排序。 但是,当我运行程序时,我得到了...
java.util.Scanner.next(Scanner.java:1530)处java.util.Scanner.throwFor(Scanner.java:909)处的线程“ main”中的java.util.InputMismatchException异常,java.util.Scanner.nextDouble( Scanner.java:2456)位于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);
}
}
我怀疑您的语言环境可能需要逗号而不是浮点数格式的点。 尝试将数据更改为
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
返回类型应该是sortCol
double[][]
。 在这种情况下,您将需要先创建原始数组的副本 void
(由于将其用作方法参数,因此不必返回对已有对象的引用) 现在,您尝试通过再次调用sortCol(matrix)
来返回double
,因此它将再次尝试返回sortCol(matrix)
(依此类推),这将导致stack overflow
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.