[英]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.