2009-05-20 23:29:27黑色狂想
2009/05/20 Datastructure Test2
public class TextAnalyze {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
manualInput(scan);
FileInput(scan);
}
private static void FileInput(Scanner scan) {
try {
System.out.println("nnn檔案處理...");
scan = new Scanner(new FileInputStream("output3.txt"));
String article = "";
while (scan.hasNextLine())
article += scan.nextLine()+" ";
scan = new Scanner(System.in);
analysis(article, scan);
} catch (FileNotFoundException ex) {
Logger.getLogger(TextAnalyze.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void analysis(String expr, Scanner scan) {
long start = System.nanoTime();
StringTokenizer stk = new StringTokenizer(expr, " #*$");
HashSet hs = new HashSet();
while (stk.hasMoreTokens()) {
String token = stk.nextToken();
if (!token.equals(" ")) {
hs.add(token.toLowerCase());
}
}
System.out.println("總共有: " + hs.size() + "個單字.");
System.out.printf("總共需時: %.5f秒n", (System.nanoTime() - start) * 1.E-9);
Stack stack = new Stack();
stack.addAll(hs);
// for (String string : hs) {
// stack.push(string);
// }
String words[] = stack.toArray(new String[0]);
System.out.println("印出未排序前堆疊中最上面的10個單字:");
for (int i = 0; i < 10; i++) {
if (i >= stack.size()) {
break;
}
System.out.print(words[i] + " ");
}
System.out.println();
start = System.nanoTime();
Collections.sort(stack, new Comparator() {
public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
return -s1.compareTo(s2);
}
});
System.out.printf("排序共費時: %.5f秒n", (System.nanoTime() - start) * 1.E-9);
System.out.print("請輸入你想顯示的單字個數: ");
int n = scan.nextInt();
System.out.printf("堆疊最上面的%d個單字是:n", n);
for (int i = 0; i < n; i++) {
if (stack.isEmpty()) {
break;
}
System.out.print(stack.pop() + " ");
}
}
private static void manualInput(Scanner scan) {
System.out.print("請輸入一段文字: ");
String expr = scan.nextLine();
analysis(expr, scan);
}
}
本文已同步發佈到「生活點滴」