java中怎样把输入的基本英文单词按首字母顺序排列?
4个回答
展开全部
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 规则:大写字母前于小写字母
*
* @author Administrator
*
*/
public class SortWords {
private static final String[] array = { "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z" };
public static void main(String[] args) {
SortWords sw = new SortWords();
List<String> words = new ArrayList<String>();
words.add("book");
words.add("ear");
words.add("alert");
words.add("choice");
words.add("name");
words.add("memery");
words.add("fight");
words.add("call");
words.add("joy");
List<String> list = sw.sort(words, "forward");
for (String str : list) {
System.out.println(str);
}
}
public List<String> sort(List<String> words, String type) {
List<Word> list = new ArrayList<Word>();
List<String> res = new ArrayList<String>();
for (String word : words) {
Word w = indexNum(word);
list.add(w);
}
switch (type) {
case "forward":
Collections.sort(list, new Forward());
for (Word w : list) {
res.add(w.getContent());
}
break;
case "back":
Collections.sort(list, new Back());
for (Word w : list) {
res.add(w.getContent());
}
break;
}
return res;
}
public Word indexNum(String word) {
String[] letters = word.split("");
String res = "";
Word w = new Word();
String letter = word.substring(0, 1);
for (int i = 0; i < array.length; i++) {
String pattern = array[i];
if (letter.equalsIgnoreCase(pattern)) {
res += i;
break;
}
}
w.setContent(word);
w.setIndexNum(Integer.parseInt(res));
return w;
}
private class Forward implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
Word w1 = (Word) arg0;
Word w2 = (Word) arg1;
int flag = w1.getIndexNum() - w2.getIndexNum();
return flag;
}
}
private class Back implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
Word w1 = (Word) arg1;
Word w2 = (Word) arg0;
int flag = w1.getIndexNum() - w2.getIndexNum();
return flag;
}
}
}
class Word {
private String content;
private Integer indexNum;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getIndexNum() {
return indexNum;
}
public void setIndexNum(Integer indexNum) {
this.indexNum = indexNum;
}
}
展开全部
用list集合试试。list集合是里放的是有顺序并且重复的东西。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
java中把排序查找等一系列算法都封装再一个叫collections的类里面有了,所以你把输入的字母存在数组或其他集合中,然后直接一句collections.sort();就排好了,你参考javaAPI中对这个类的详解会更吃惊的,呵呵呵
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
ASC码是按字母序的 所以你可以用asc码来排序
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询