用java写一个英语词典程序

我提供简单的代码示例供您参考。

  1. 单词录入、查询、排序、删除、修改、文件存储:
import java.io.*;
import java.util.*;

public class WordDictionary {
    private Map<String, String> words;

    public WordDictionary() {
        this.words = new TreeMap<>();
    }

    public boolean addWord(String spelling, String meaning) {
        if (words.containsKey(spelling)) {
            System.out.println("该单词已经存在,请修改或者删除该单词。");
            return false;
        } else {
            words.put(spelling.toLowerCase(), meaning);
            return true;
        }
    }

    public String searchWord(String spelling) {
        if (words.containsKey(spelling.toLowerCase())) {
            return words.get(spelling.toLowerCase());
        } else {
            return null;
        }
    }

    public void sortWords() {
        Set<Map.Entry<String, String>> entrySet = words.entrySet();
        List<Map.Entry<String, String>> list = new ArrayList<>(entrySet);
        list.sort(Map.Entry.comparingByKey());
        words = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : list) {
            words.put(entry.getKey(), entry.getValue());
        }
    }

    public boolean removeWord(String spelling) {
        if (words.containsKey(spelling.toLowerCase())) {
            words.remove(spelling.toLowerCase());
            return true;
        } else {
            System.out.println("该单词不存在,无法删除。");
            return false;
        }
    }

    public boolean modifyWord(String spelling, String meaning) {
        if (words.containsKey(spelling.toLowerCase())) {
            words.put(spelling.toLowerCase(), meaning);
            return true;
        } else {
            System.out.println("该单词不存在,无法修改。");
            return false;
        }
    }

    public void saveToFile(String fileName) {
        try (PrintWriter output = new PrintWriter(new FileWriter(fileName))) {
            for (Map.Entry<String, String> entry : words.entrySet()) {
                output.println(entry.getKey() + ":" + entry.getValue());
            }
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    public void readFromFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }
        try (Scanner input = new Scanner(file)) {
            while (input.hasNext()) {
                String line = input.nextLine();
                String[] parts = line.split(":");
                words.put(parts[0].toLowerCase(), parts[1]);
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
  1. 模糊查询:
public List<String> fuzzySearch(String spelling) {
    List<String> result = new ArrayList<>();
    for (String key : words.keySet()) {
        if (key.startsWith(spelling.toLowerCase()) || key.contains(spelling.toLowerCase())) {
            result.add(key + ": " + words.get(key));
        }
    }
    return result;
}
  1. 语音朗读:
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine.Info;

import javazoom.spi.PropertiesContainer;


public class WordDictionary {
    private Map<String, String> words;

    ...

    public void speakWord(String spelling) {
        String apiUrl = "http://dict.youdao.com/dictvoice?type=2&audio=%s";
        String url = String.format(apiUrl, URLEncoder.encode(spelling));
        try (AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new URL(url))){
            PropertiesContainer.setResponseProperties(new Properties());
            Clip clip = AudioSystem.getClip();
            clip.open(audioInputStream);
            clip.start();
        } catch (Exception ex) {
            System.out.println("Error occurred while playing sound: " + ex.getMessage());
        }
    }
}
  1. 自动更新单词库:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class WordDictionary {
    private static final String API_URL = "https://api.dictionaryapi.dev/api/v2/entries/en/";

    private Map<String, String> words;

    ...

    public boolean updateWords(String spelling) {
        String url = API_URL + spelling;
        try (Scanner input = new Scanner(new URL(url).openStream())) {
            StringBuilder response = new StringBuilder();
            while (input.hasNextLine()) {
                response.append(input.nextLine());
            }
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(response.toString());
            JsonObject json = element.getAsJsonArray().get(0).getAsJsonObject();
            String meaning = json.get("meanings").getAsJsonArray().get(0)
                    .getAsJsonObject().get("definitions").getAsJsonArray().get(0)
                    .getAsJsonObject().get("definition").getAsString();
            words.put(spelling, meaning);
            return true;
        } catch (IOException ex) {
            System.out.println("Error occurred while updating words: " + ex.getMessage());
            return false;
        }
    }
}
  1. 导出单词列表:
public void exportWords(String fileName) {
    try (PrintWriter output = new PrintWriter(new FileWriter(fileName))) {
        output.println("Spelling\tMeaning");
        for (Map.Entry<String, String> entry : words.entrySet()) {
            output.println(entry.getKey() + "\t" + entry.getValue());
        }
    } catch (IOException ex) {
        System.out.println("Error occurred while exporting words: " + ex.getMessage());
    }
}
  1. 历史记录:
public class QueryHistory {
    private List<String> history;

    public QueryHistory() {
        this.history = new ArrayList<>();
    }

    public void addQuery(String query) {
        history.add(query);
    }

    public List<String> getHistory() {
        return new ArrayList<>(history);
    }

    public void clearHistory() {
        history.clear();
    }
}

以上代码只是简单示例,可根据您的实际需求进行修改,并非完整代码。

 

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

需要什么私信我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值