[問題] 文字資料排序

看板java作者 (我只怕北京張寶成)時間16年前 (2008/05/19 13:36), 編輯推噓5(504)
留言9則, 5人參與, 最新討論串1/1
我有一筆通訊資料裡面記載 name, phone, email 只有 name 是必需的 phone 跟 email 可有可無 文字檔內容如下: name pc mxn phone 3246436 email pcmxn@mail.org name fire ox email fireox@isp.org name kk mxn phone 2135455 email kkmxn@mail.com 我想對這個文字檔作排序 e.g. 依 name 排序、或是依 phone 排序 目前只作了依 name 的排序 不過輸出的資料只有第一筆 應該是讀進來的資料在第一個迴圈就用掉了 所以第二、第三沒有資料可讀 不知道該怎麼寫才行 另外,如果想對 phone 或是 email 排序,該怎麼作呢 跟 name 的排序好像不太一樣 程式碼如下: import java.util.*; import java.io.*; import java.lang.*; public class Main { public static void main(String[] args) throws Exception{ String inputfile = "input.txt"; String outputfile = "output.txt"; String[] person = new String[3]; FileReader input1 = new FileReader(inputfile); Scanner content1 = new Scanner(input1); String str; int count = 0; // 找出資料內的全部姓名並且存在 person 裡面 while (content1.hasNext()){ str = content1.next(); if (str.equals("name")){ person[count] = content1.next()+" "+content1.next(); count += 1; } } // 將 person 排序 Arrays.sort(person); String newLine = System.getProperties().getProperty("line.separator"); FileWriter output = new FileWriter(outputfile,true); BufferedReader input = new BufferedReader(new FileReader(inputfile)); String line; // 因為有三筆資料,所以將資料讀取三次 for (int i=0;i<3;i++){ input = new BufferedReader(new FileReader(inputfile)); Scanner content = new Scanner(input); while (content.hasNextLine()){ line = content.nextLine(); if (line.indexOf(person[i])>=0){ // 如果該行有這個 name 就將該行寫入 output 直到讀到空白行 while (!line.trim().equals("")){ output.write(line + newLine); line = content.nextLine(); } } } } input.close(); output.close(); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.225.166.232

05/19 17:09, , 1F
我有寫過類似的, 我是把他存成一個Object,
05/19 17:09, 1F

05/19 17:11, , 2F
Person(String name, String phone, String e-mail)
05/19 17:11, 2F

05/19 17:11, , 3F
那要怎麼做 object 根據某項資料的排序呢?
05/19 17:11, 3F

05/19 17:14, , 4F
你在線上哦...?我的msn: iensue@msn.com
05/19 17:14, 4F

05/19 19:36, , 5F
先存成object 再implements Comparable~ 這是關鍵步驟
05/19 19:36, 5F

05/19 20:10, , 6F
欲抽換排序方法可用Comparator
05/19 20:10, 6F

05/19 20:34, , 7F
現在排序大概是沒問題了,不過在處理文字檔時我是用暴力法
05/19 20:34, 7F

05/19 20:37, , 8F
把 name、phone、email抽出來丟給 object,有比較好的方法嗎
05/19 20:37, 8F

05/22 17:02, , 9F
你的文字檔可以考慮用csv的檔案格式
05/22 17:02, 9F
文章代碼(AID): #18CH7C40 (java)