相信百度翻译对于大家来说并不陌生,本案例要求编写一个程序模拟百度翻译。用户输入英文之后搜索程序中对应的中文,如果搜索到对应的中文就输出搜索结果,反之给出提示。本案例要求使用Map集合实现英文与中文的存储。
实现英汉互译
代码如下
package lianxi;
import java.util.*;
public class Lianxi21_2 {
public static void main(String[] args) {
HashMap<String, String> map=new HashMap<>();
map.put("苹果", "apple");
map.put("好的", "good");
map.put("大地", "land");
Scanner in=new Scanner(System.in);
System.out.println("请输入字符:");
String a=in.next();
for (Map.Entry<String,String> roo:map.entrySet()){//在roo中存入map中的键和值,并且遍历
if (roo.getValue().equals(a)){//如果此时roo的值等于输入的值
System.out.println(a + " 的中文是:"+roo.getKey());
}
if(roo.getKey().equals(a)) {//如果此时roo的键等于输入的键
System.out.println(a + " 的英文是:"+roo.getValue());
}
}
}
}
运行结果