java急救寫一程式可輸入十個字串,然後依照這些字串長短依序

寫一程式可輸入十個字串,然後依照這些字串長短依序輸出

(先印出短字串在印出較長字串)

1 Answer

Rating
  • Jeremy
    Lv 4
    1 decade ago
    Favorite Answer

    import java.util.*;

     

    class MyStringComparator implements Comparator {

      //由小到大的順序比較

      public int compare(String s1, String s2) {

        int diff = s1.length() - s2.length();

        if (diff == 0) {

          return s1.compareTo(s2);

        } else {

          return diff;

        }

      }

    }

     

    public class Ex1 {

      

      public static void main(String[] args) {

        String [] name = new String[10];

        TreeSet tm = new TreeSet (new MyStringComparator());

        Iterator itr;

        

        //英文名子

        name[0] = "Barbara";

        name[1] = "Elizabeth";

        name[2] = "Helen";

        name[3] = "Katharine";

        name[4] = "Lee";

        name[5] = "Johnson";

        name[6] = "Ann";

        name[7] = "Diana";

        name[8] = "Bill";

        name[9] = "Fiona";

        

        //新增資料

        for (int i = 0; i < name.length; i++) {

          tm.add(name[i]);

        }

        

        //印出結果

        itr = tm.iterator();

        while (itr.hasNext()) {

          System.out.println(itr.next());

        }

      }

    }

    2008-05-01 13:54:20 補充:

    執行結果:

     

    Ann

    Lee

    Bill

    Diana

    Fiona

    Helen

    Barbara

    Johnson

    Elizabeth

    Katharine

    2008-05-01 13:56:12 補充:

     

    如果要先印出 "長" 字串在印出較 "短"字串

    把這一行

     

     itr = tm.iterator();

     

    改成反向輸出

     

     itr = tm.descendingIterator();

    -------------------

    執行結果如下:

    Katharine

    Elizabeth

    Johnson

    Barbara

    Helen

    Fiona

    Diana

    Bill

    Lee

    Ann

    2008-05-01 13:58:24 補充:

    如何實做比較器:

    (1) 繼承 Comparator 介面,並實做比較的方法 Compare(T1, T2)

    (2) 比較的方法是採用字串長度,如果字串長度相同,則依序比較字母

    2008-05-01 13:58:29 補充:

    class MyStringComparator implements Comparator {

      //由小到大的順序比較

      public int compare(String s1, String s2) {

        int diff = s1.length() - s2.length();

        if (diff == 0) {

          return s1.compareTo(s2);

        } else {

          return diff;

        }

      }

    }

    2008-05-01 14:00:08 補充:

    除了使用集合物件來實做外,

    也可以使用陣列方式來實做~

    在使用 Arrays 物件的排序方法來排序

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.