Anonymous
Anonymous asked in 電腦與網際網路程式設計 · 1 decade ago

JAVA檔案-讀檔之後印出~急!!

我要寫一個程式:

在要讀的檔案(input.dat)裡輸入字母

記事本(input.dat)打上:

{1,2,3,4,5}

{ab,cd,efg}

讀檔印出後:

{5,4,3,2,1} 數字部分直接反向印出

{ba,dc,gfe} 英文部分反向但未置不變

請高手指點^^謝謝

Update:

麻煩請說明每行及註解的意思謝謝@@

Update 2:

氣泡排序太複雜ㄌ~可以用簡單一點ㄉ方法咩??感謝^^"

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    請參考我的做法

    import java.io.*;import java.util.*;public class Y5594 { public static void main(String[] args) throws Exception { // using scan to read input.dat one line at a time Scanner scan = new Scanner(new File("input.dat")); while (scan.hasNext()) { // using scan2 to read each element, seperated by non-word // character, in the array Scanner scan2 = new Scanner(scan.next()).useDelimiter("\\W"); // using ArrayList to keep the elements ArrayList<String> al = new ArrayList<String>(); while (scan2.hasNext()) { al.add(scan2.next()); } // if empty ArrayList, jump to the next line if (al.size() == 0) continue; // copy the elements to a string ary for sorting String[] ary = new String[al.size()]; // seperate int array from string array boolean isDigitArray = Character.isDigit(al.get(0).charAt(0)); for (int i = 0; i < ary.length; i++) { if (isDigitArray) { // if int array, simply copy it ary[i] = al.get(i); } else { // if string array, reverse the character order within ary[i] = new StringBuffer(al.get(i)).reverse().toString(); } } // sort the array order if only int array if (isDigitArray) Arrays.sort(ary); System.out.print("{"); for (int i = 0; i < ary.length; i++) { if (isDigitArray) { // if int array, print the elements in backward order System.out.print(ary[ary.length-1-i]); } else { // if string array, simply print it System.out.print(ary[i]); } // print the separater "," if not the last element if (i != ary.length-1) System.out.print(","); } System.out.println("}"); } }}

    2008-11-01 23:38:05 補充:

    我在重要的程式碼前後都已經加註註解了。

    2008-11-01 23:38:38 補充:

    這段程式碼並沒有用到氣泡排序唷。

Still have questions? Get your answers by asking now.