以下是使用 Java 实现英语单词和中文单词互译的代码示例:

import java.util.HashMap;
import java.util.Map;

public class Translation {
    private Map<String, String> dictionary = new HashMap<>();

    public Translation() {
        // 初始化字典
        dictionary.put('hello', '你好');
        dictionary.put('world', '世界');
        dictionary.put('java', 'Java');
        dictionary.put('programming', '编程');
    }

    public String translate(String word) {
        // 检查字典中是否存在对应的中文翻译
        if (dictionary.containsKey(word)) {
            return dictionary.get(word);
        } else {
            return '未知单词';
        }
    }
}

在上面的代码中,我们定义了一个Translation类来实现Java英语单词和中文单词的互译。我们使用HashMap来存储英语单词和中文单词之间的对应关系。在translate方法中,我们首先检查字典中是否存在对应的中文翻译,如果存在则返回对应的中文单词,否则返回一个默认的未知单词。


原文地址: https://www.cveoy.top/t/topic/nxSU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录