编写一个java程序模拟百度翻译。用户输入英文之后搜索程序中对应的中文,如果搜索到对应的中文就输出搜索结果,反之给出提示。本案例要求使用Map集合实现英文与中文的存储。
时间: 2024-02-27 08:57:53 浏览: 32
好的,以下是 Java 程序的实现:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class BaiduTranslator {
public static void main(String[] args) {
Map<String, String> dictionary = new HashMap<String, String>();
dictionary.put("apple", "苹果");
dictionary.put("banana", "香蕉");
dictionary.put("cherry", "樱桃");
dictionary.put("orange", "橙子");
dictionary.put("watermelon", "西瓜");
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要翻译的英文单词:");
String word = scanner.nextLine();
if (dictionary.containsKey(word)) {
System.out.println("翻译结果:" + dictionary.get(word));
} else {
System.out.println("抱歉,没有找到对应的中文翻译。");
}
}
}
```
程序首先创建了一个 HashMap 对象,用于存储英文单词和对应的中文翻译。然后通过 Scanner 类获取用户输入的英文单词,使用 containsKey() 方法判断该单词是否在 HashMap 中存在,如果存在则输出对应的中文翻译,否则输出提示信息。