質問: java急救寫一程式可輸入十個字串,然後依照這些字串長短依序 寫一程式可輸入十個字串,然後依照這些字串長短依序輸出 (先印出短字串在印出較長字串)
回答: 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 物件的排序方法來排序