(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class test {
public static void main(String[] args) {
String str = "hello java I like java very much";
String[] items = str.split(" ");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String s : items) {
if (map.containsKey(s))
map.put(s, map.get(s) + 1);
else {
map.put(s, 1);
}
}
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();
for (Entry<String, Integer> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list, new EntryComparator());
for (Entry<String, Integer> obj : list) {
System.out.println(obj.getKey() + "\t" + obj.getValue());
}
}
}
class EntryComparator implements Comparator<Entry<String, Integer>> {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue() > o2.getValue() ? 0 : 1;
}
}
(2)把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;
import java.util.Scanner;
public class test2 {
public static void main (String[] args){
test2 a = new test2();
a.View();
}
public void findWord(String str){
String[] arrayWord =str.split(" ");
for(int i=arrayWord.length-1;i>=0;i--){
System.out.print(arrayWord[i]+" ");
}
}
public void View(){
Scanner input =new Scanner(System.in);
System.out.print("请输入一段英文,回车结束:");
String str=input.nextLine();
test2 a = new test2();
System.out.println("倒叙结果:");
a.findWord(str);
}
}