2014-02-23 82 views
-3

所以我這裏有這個代碼,需要一個文件,並將其放入一個數組。我現在需要做的是將第二列中的整數從大到小排序。這裏是我的代碼,並在底部有一個指向數據文件的鏈接。我知道有排序算法,但我不知道如何實現它們。整數數組排序

import java.util.*; 
import java.io.*; 
public class sorter{ 
public static int id = 0; 
public static int score = 0; 
public static void main(String args[]){ 
Scanner inFile = null; 
      try { 
    inFile = new Scanner (new File ("sorter.txt")); 
} catch (FileNotFoundException e) { 
    System.out.println("File not found!"); 
    System.exit(0); 
    } 
while (inFile.hasNextLine()){ 
    String str = inFile.nextLine(); 
    String [] parts = str.split(" "); 
    String part1 = parts[0]; 
    String part2 = parts[1]; 
    id = Integer.parseInt(part1); 
    score = Integer.parseInt(part2); 
    System.out.println(part1 + " " +part2); 
} 
} 
    } 

這裏是輸出應該是什麼:

/* 
ID​ Score 
305​ 265 
306​ 262 
115 ​257 
311 ​256 
123 ​253 
116​ 246 
325 ​246 
321 ​245 
323 ​245 
113 ​243 
218 ​243 
208 ​242 
302 ​242 
112 ​239 
104 ​239 
110 ​238 
223 ​230 
213​ 229 
207 ​228 
203 ​224 
222 ​223 
    */ 

Link to data file

+1

那麼通常情況下,你不不必執行它們。我會看看Java Arrays API。我相信你可以用一種排序數組的方式來。試着在紙上畫出你將如何排序一個小陣列 –

+0

@ user3259415你是按ID還是Score排序? – Mozzie

+0

那麼,你應該先救每一個得分/ ID,排序它然後通過分數打印 –

回答

1

我將創建一個類來處理這個問題。

class Data { 
    private int id; 
    private int score; 

    //constructor and other stuff 
} 

既然你都這樣了,創建一個List來保存你所有的DATAS

List<Data> list = new ArrayList<>(); 
while (inFile.hasNextLine()){ 
    String str = inFile.nextLine(); 
    String [] parts = str.split(" "); 
    list.add(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); 
} 

現在,你有這份名單中,你可以對它進行排序。但是如何?

這裏的API來救援!有一個在Collections類(稱爲sort),它可以讓你排序列表,使用自定義Comparator的方法。

因此,你需要什麼是創造你的比較,將通過他們的分數比較你的對象:

static class DataComparator implements Comparator<Data> { 
    @Override 
    public int compare(Data d1, Data d2){ 
     return Integer.compare(d1.getScore(), d2.getScore()); 
    } 
} 

現在,你擁有了這些,只需要調用Collections.sort

Collections.sort(list, new DataComparator()); 
+0

那麼一個創建列表的類以及另一個包含dataComparator和Data類的類?我很新,所以它仍然有點混亂。 – user3259415

+0

@叫'Data' user3259415一類,將持有的ID和得分在文件中的每個條目,一個創造了比較(你可以讓你的類實現可比的接口,但我認爲這是最好創建一個自定義的比較,因爲它更靈活,並不明顯(而且可能要在將來改變!)你的數據都是通過分數,而不是IDS來分類的。名單('ArrayList'類)已經存在於JDK。 –