(1)写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。(单词之间用空格隔开,如“Hello World My First Unit Test”);
package cn.chen.guan;
import java.util.HashMap;
import java.util.Map;
public class Number {
private Map<String,Integer> wordsMap;
public Number(String strs){
wordsMap=this.getArray(strs);
}
public Map<String ,Integer> getArray(String strs){
String[] words_Array=strs.split(" ");
Map<String,Integer> words_Map=new HashMap<String,Integer>();
int arrLength=words_Array.length;
for(int i=0;i<arrLength;i++){
if(!words_Map.containsKey(words_Array[i])){
words_Map.put(words_Array[i],1);
}
else{
int currentNum=words_Map.get(words_Array[i])+1;
words_Map.remove(words_Array[i]);
words_Map.put(words_Array[i],currentNum);
}
}
return words_Map;
}
}
package cn.chen.guan;
import java.util.Scanner;
public class Testnumber {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String strs=scan.nextLine();
Number num=new Number(strs);
num.getArray(strs);
}
}
(2)把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”;
package com.chen.guan;
import java.util.Scanner;
public class ReverseString {
public void calculate(String str1){
Scanner scan = new Scanner(System.in);
System.out.println("请输入句子:");
String[] strArr = scan.nextLine().split("\s+|[,]");
StringBuffer result = new StringBuffer();
for(int i = strArr.length -1;i >=0; i--){
result.append(strArr[i] + " ");
}
result.setCharAt(scan.nextLine().length()-0, ' ');
System.out.println("结果是:"+result.toString());
}
}
package com.chen.guan;
import java.util.Scanner;
public class TestRevereString {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ReverseString rs=new ReverseString();
Scanner scan = new Scanner(System.in);
String str=scan.nextLine();
System.out.println("请输入句子:");
rs.calculate(str);
}
}