第一题:
package songjiaming;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class shushu {
public void countWord(String str) {
String[] wordsArray = str.split(" ");
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
for (String word : wordsArray) {
if (wordsMap.containsKey(word)) {
wordsMap.put(word, wordsMap.get(word) + 1);
} else {
wordsMap.put(word, 1);
}
}
Set<String> setKey = wordsMap.keySet();
Iterator<String> itKey = setKey.iterator();
while (itKey.hasNext()) {
String word = itKey.next().toString();
int count = wordsMap.get(word);
System.out.println("单词 " + word + " 出现" + count + "次");
}
}
}
JUnit测试
package songjiaming;
import static org.junit.Assert.*;
import org.junit.Test;
public class shushuTest {
@Test
public void testCountWord() {
shushu s1= new shushu();
s1.countWord("Hello World My First Unit Test Test");
}
}
第二题:
package com.song.work2;
import java.util.Scanner;
public class diandao {
public static void reverse(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入相应的英文:");
String str = input.nextLine();
String[] strArr = str.split("\s+|[,]");
StringBuffer result = new StringBuffer();
for (int i = strArr.length - 1; i >= 0; i--) {
result.append(strArr[i] + " ");
}
result.setCharAt(str.length() - 0, ' ');
System.out.println("颠倒顺序后的结果为:" + result.toString());
}
}
Junit测试代码如下:
package com.song.work2;
import static org.junit.Assert.*;
import org.junit.Test;
public class Question2Test {
@Test
public void test() {
Question2 q2 = new Question2();
q2.reverse(null);;
}
}