作者amike (我只怕北京张宝成)
看板java
标题[问题] 文字资料排序
时间Mon May 19 13:36:11 2008
我有一笔通讯资料里面记载 name, phone, email
只有 name 是必需的 phone 跟 email 可有可无
文字档内容如下:
name pc mxn
phone 3246436
email
[email protected]
name fire ox
email
[email protected]
name kk mxn
phone 2135455
email
[email protected]
我想对这个文字档作排序
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
1F:推 iensue:我有写过类似的, 我是把他存成一个Object, 05/19 17:09
2F:→ iensue:Person(String name, String phone, String e-mail) 05/19 17:11
3F:→ amike:那要怎麽做 object 根据某项资料的排序呢? 05/19 17:11
5F:推 keter:先存成object 再implements Comparable~ 这是关键步骤 05/19 19:36
6F:推 ClareQ:欲抽换排序方法可用Comparator 05/19 20:10
7F:→ amike:现在排序大概是没问题了,不过在处理文字档时我是用暴力法 05/19 20:34
8F:→ amike:把 name、phone、email抽出来丢给 object,有比较好的方法吗 05/19 20:37
9F:推 jayfish:你的文字档可以考虑用csv的档案格式 05/22 17:02