作者amike (我只怕北京張寶成)
看板java
標題[問題] 文字資料排序
時間Mon May 19 13:36:11 2008
我有一筆通訊資料裡面記載 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
推 iensue:我有寫過類似的, 我是把他存成一個Object, 05/19 17:09
→ iensue:Person(String name, String phone, String e-mail) 05/19 17:11
→ amike:那要怎麼做 object 根據某項資料的排序呢? 05/19 17:11
推 iensue:你在線上哦...?我的msn: iensue@msn.com 05/19 17:14
推 keter:先存成object 再implements Comparable~ 這是關鍵步驟 05/19 19:36
推 ClareQ:欲抽換排序方法可用Comparator 05/19 20:10
→ amike:現在排序大概是沒問題了,不過在處理文字檔時我是用暴力法 05/19 20:34
→ amike:把 name、phone、email抽出來丟給 object,有比較好的方法嗎 05/19 20:37
推 jayfish:你的文字檔可以考慮用csv的檔案格式 05/22 17:02