2015-10-15 167 views
0

我有兩個數組,其中一個數組代表一個名稱集合,另一個描述它們的關聯標記。我想按升序對數組中的標記進行排序,然後還將各個名稱與商標有關。通過對數組進行排序創建排名列表

我的目標是創建一個排名列表。我正在使用Processing來做到這一點

float sum = 0; 

String [] name = {"A", "B", "C", "D","E"}; 
float [] mark = {12, 2, 4, 6, 23}; 

void setup() { 

    size(600, 600); 
    smooth(); 
} 

void draw() { 
    background(225); 
    fill(0); 
    println(name.length); 
    for (int i =0; i<name.length; i++) { 
    text(name[i] + ":"+ mark[i], 100, 100+i*50); 
    } 
} 

/////// i wanted to sort it as E:23, A:12, D:6,  C:4,  B:2 

如果有人能幫助我,這將是非常好的。 :)

提前許多感謝, 優素福

+1

你能在代碼中指定的語言嗎?看起來像C,但要確定...另外,您使用的各種功能看起來都來自庫 - 可能是Processing庫? –

+0

Hi @MichaelDorgan我正在使用基於Java的處理程序 –

+0

爲什麼你使用兩個「數組」? [地圖](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html)將是一個更好的選擇 – sam

回答

1

可以使數據holder類實現Comparable。我認爲你也可以使用Map,就像一個hashMap。

這裏數據holder類例如:

import java.util.Collections; 

ArrayList <Data> d = new ArrayList<Data>(); 

void setup() { 
    size(600, 600); 

    d.add(new Data("A", 12)); 
    d.add(new Data("B", 2)); 
    d.add(new Data("C", 4)); 
    d.add(new Data("D", 6)); 
    d.add(new Data("E", 23)); 



    println("before sorting:\n" + d); 

    //used reverseOrder as it goes decrescent, but you could just reverse 
    //the "natural" order in the class it self. Exchange -1 and 1 in compareTo() 
    // and use Collections.sort(d); here 
    Collections.sort(d, Collections.reverseOrder()); 

    println("after sorting:\n" + d); 
} 


/////// i wanted to sort it as E:23, A:12, D:6,  C:4,  B:2 


class Data implements Comparable { 
    String name; 
    int mark; 

    Data(String _n, int _m) { 
    name = _n; 
    mark = _m; 
    } 

    // this sets the 'natural' order of Data 
    @Override 
    int compareTo(Object o) { 
    Data other = (Data) o; 

    if (other.mark > mark) { 
     return -1; 
    } else if (other.mark < mark) { 
     return 1; 
    } 
    return 0; 
    } 


    // this to get a nice looking output in console... 
    @Override 
    String toString() { 
    return name + ":" + nf(mark, 2); 
    } 
} 
+0

非常感謝@ v.k。代碼運行良好。我現在必須開始瞭解地圖:) –

+0

還有[intDict](https://processing.org/reference/IntDict.html),您可以嘗試 –

相關問題