2015-11-08 201 views
4

需求是對二維數組的行進行排序。我覺得我的代碼非常接近完成,但我不明白爲什麼它不顯示排序的數組。我忘了提及我們不允許使用預製分類方法。這個問題很可能在sortRows方法中。不管怎麼說,這裏是我的代碼:按行排序二維陣列

public class RowSorting 
{ 
    public static void main(String[] args) 
{ 
    double[][] numbers = new double[3][3]; 
    double[][] number = new double[3][3]; 
    int run = 0; 
    String answer = ""; 

    while (run == 0) 
    { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter a 3-by-3 matrix row by row: "); 
     for(int row = 0; row < numbers.length; row++) 
     { 
     for(int column = 0; column < numbers[row].length; column++) 
      { 
      numbers[row][column] = input.nextDouble(); 
      } 
     } 
     for(int row = 0; row < numbers.length; row++) 
     { 
     for(int column = 0; column < numbers[row].length; column++) 
      { 
      System.out.print(numbers[row][column] + " "); 
      } 
     System.out.print("\n"); 
     } 
     System.out.println("The sorted array is: \n"); 
     number = sortRows(numbers); 
     for(int row = 0; row < number.length; row++) 
     { 
     for(int column = 0; column < number[row].length; column++) 
      { 
      System.out.print(number[row][column] + " "); 
      } 
     System.out.print("\n"); 
     } 




    System.out.print("\nWould you like to continue the program (y for yes or anything else exits): "); 
     answer = input.next(); 

     if(answer.equals("y")) 
     { 
     continue; 
     } 
     else 
     break; 
     } 




} 
public static double[][] sortRows(double[][] m) 
{ 
    for(int j = 0; j < m[j].length - 1; j++) 
    { 
    for(int i = 0; i < m.length; i++) 
    { 
     double currentMin = m[j][i]; 
     int currentMinIndex = i; 

     for(int k = i + 1; k < m[j].length; k++) 
     { 
     if(currentMin > m[j][i]) 
     { 
     currentMin = m[j][i]; 
     currentMinIndex = k; 
     } 
     } 
    if(currentMinIndex != i) 
    { 
    m[currentMinIndex][j] = m[j][i]; 
    m[j][i] = currentMin; 
    } 
    } 
    } 
    return m; 
} 
} 

回答

1

它看起來像塊:

if(currentMin > m[j][i]) 
    { 
    currentMin = m[j][i]; 
    currentMinIndex = k; 
    } 

永遠不會發生。因爲您剛剛將currentMin分配給m [j] [i]之前的兩行。如果檢查,我相信你想用k。像

if (currentMin > m[j][k]){ 
    currentMin = m[j][k]; 
    currentMinIndex = k; 
} 
+1

哦,是的!非常感謝。這是我的問題的固定部分,但我能夠玩弄它來弄清楚。我還必須翻轉currentMinIndex變量和j。非常感謝!!! –

0

按ergonaut引用的東西,你有問題的代碼塊

if(currentMin > m[j][i]) ... 

m[currentMinIndex][j] = m[j][i]; 

但是,你也有一個問題,您的for循環。

for(int j = 0; j < m[j].length - 1; j++) ... 
    for(int i = 0; i < m.length; i++) ... 

這兩個都是奇怪的結構。您可能想要交換這些for-loops,以便不拋出索引異常。這也會導致您在代碼中尋址索引。並修改您的j-index for-loop以包含整個範圍。