輸入:建立一個文字檔INPUT.TXT內容為為每一行一個字
輸出:開啟INPUT.TXT,讀入檔案中 資料,將資料排序(從小到 ),將資料輸出到OUTPUT.TXT格式仍然是每一行一個數字
2007-01-21 19:39:26 · 2 個解答 · 發問者 熊 1 in 電腦與網際網路 ➔ 程式設計
請參考我的做法。
import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(new File("input.txt"));
ArrayList al = new ArrayList();
while (input.hasNextLine()) {
al.add(input.nextLine());
}
input.close();
int[] ary = new int[al.size()];
for (int i = 0; i < ary.length; i++) {
ary[i] = Integer.parseInt((String)al.get(i));
}
Arrays.sort(ary);
PrintWriter output = new PrintWriter(new File("output.txt"));
for (int i = 0; i < ary.length; i++) {
output.println(ary[i]);
}
output.close();
}
}
2007-01-23 12:00:10 · answer #1 · answered by ? 7 · 0⤊ 0⤋
TreeSet
try {
BufferedReader BR =
new BufferedReader(new FileReader(new File("INPUT.TXT")));
String getStr = null;
while((getStr = BR.readLine())!=null)
set.add(getStr);
BR.close();
} catch (FileNotFoundException e) {
} catch (IOException ioe){
}
try {
BufferedWriter BW =
new BufferedWriter(new FileWriter(new File("OUTPUT.TXT")));
Iterator
while(it.hasNext()){
BW.write(it.next());
BW.newLine();
}
BW.close();
} catch (FileNotFoundException e) {
} catch (IOException ioe){
}
2007-01-21 22:44:37 · answer #2 · answered by ? 1 · 0⤊ 0⤋