2013-11-28 180 views
0

我有一個帶有學生名稱和帶有學生標記的2D數組的單個分區數組,我可以對名稱進行排序,但我無法獲得匹配的標記(因爲他們必須留在相同的順序)。這是我嘗試代碼:數組排序多維數組以匹配第二個數組

static String[] studentNamesArray = new String[10]; 
static int[][] studentMarksArray = new int[10][3]; 

    static void sortAlphabetical() { 
    String tempName; 
    int intSwap; 
    boolean flag = false; 
    while (flag==false) { 
     flag = true; 
     for (int i = 0; i < 9; i++) { 
     if (studentNamesArray[i].compareTo(studentNamesArray[i + 1])>0) { 
      tempName = studentNamesArray[i]; 
      studentNamesArray[i] = studentNamesArray[i + 1]; 
      studentNamesArray[i + 1] = tempName; 

      for(int y=0;y<2;y++){ 
      intSwap = studentMarksArray[i][0]; 
      studentMarksArray[i][y] = studentMarksArray[i+1][y+1]; 
      studentMarksArray[i+1][y+1] = intSwap; 
      } 
      flag = false; 
     } 
     } 
    } 
    } 
+1

任何你不想創建一個擁有名稱和標記的Student對象,然後創建crea te'Student []'數組,並使用「比較器」按名稱排序? –

+0

我只限於非OO方法 – Colin747

+0

'compareTo'是一種OO方法... – brimborium

回答

3

你只需要交換標記陣列像你這樣的名字:

static void sortAlphabetical() { 
     String tempName; 
     int [] intSwap; //<-- note I changed this as an int[] array 
     boolean flag = false; 
     while (flag==false) { 
      flag = true; 
      for (int i = 0; i < studentNamesArray.length-1; i++) { //<-- note I changed this to length - 1 to avoid IndexOutOfBoundsException 
      if (studentNamesArray[i].compareTo(studentNamesArray[i + 1])>0) { 
       tempName = studentNamesArray[i]; 
       studentNamesArray[i] = studentNamesArray[i + 1]; 
       studentNamesArray[i + 1] = tempName; 

       intSwap = studentMarksArray[i]; 
       studentMarksArray[i] = studentMarksArray[i+1]; 
       studentMarksArray[i+1]= intSwap; 
       flag = false; 
      } 
      } 
     } 
     } 

static String[] studentNamesArray = new String[3]; 
    static int[][] studentMarksArray = new int[3][3]; 

    public static void main (String[] args) throws java.lang.Exception { 
     studentNamesArray[0] = "Mark"; 
     studentNamesArray[1] = "Anna"; 
     studentNamesArray[2] = "Arnold"; 

     studentMarksArray[0] = new int[]{1,2,3}; 
     studentMarksArray[1] = new int[]{4,5,6}; 
     studentMarksArray[2] = new int[]{0,0,0}; 

     sortAlphabetical(); 
     System.out.println(Arrays.toString(studentNamesArray)); 
     System.out.println(Arrays.deepToString(studentMarksArray)); 

    } 

輸出:

[Anna, Arnold, Mark] 
[[4, 5, 6], [0, 0, 0], [1, 2, 3]] 
+0

您能解釋爲什麼您將'intSwap'更改爲數組嗎? – Colin747

+1

@ Colin747因爲最初每個標記數組都與String數組對應的索引位置相同?所以如果你在數組中交換了兩個名字,你也要交換相應的標記數組。 –

+0

我不是在質疑你爲什麼這麼做,我只是想確保我正確理解發生了什麼,你的解決方案工作得很好,謝謝 – Colin747