class WordPolice implements ActionListener { WindowWord view; HashMap<String,String>hashtable; File file = new File ("E:\\JAVA\\上机\\作业5\\cet4.txt"); Scanner sc = null ; WordPolice () { hashtable = new HashMap< String,String >(); //System.out.println(hashtable.size()); try { sc = new Scanner ( file ); //System.out.println(sc); while (sc.hasNext ()) { String englishWord = sc . next (); String chineseWord = sc . next (); hashtable . put ( englishWord , chineseWord ); } } catch(Exception e ) {} } public void setView(WindowWord view) { this.view = view; } public void actionPerformed(ActionEvent e) { String englishWord = view.inputText.getText (); if(hashtable.containsKey(englishWord)) { String chineseWord = hashtable.get ( englishWord ); view.showText.setText ( chineseWord ); } else { view.showText.setText ("没有此单词"); } } }把这段代码完善一下,让它能实现汉语翻译为英语
时间: 2023-11-22 13:53:27 浏览: 57
可以在原有的 WordPolice 类中新增一个方法,用于将HashMap中的键值对反转,即将汉语作为键,英语作为值。同时,在 actionPerformed 方法中加入判断,如果输入的是中文,则调用新加的方法进行翻译。
完整代码如下:
```
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.Scanner;
public class WordPolice implements ActionListener {
WindowWord view;
HashMap<String,String> hashtable;
File file = new File("cet4.txt");
Scanner sc = null;
WordPolice () {
hashtable = new HashMap<String,String>();
try {
sc = new Scanner(file);
while (sc.hasNext()) {
String englishWord = sc.next();
String chineseWord = sc.next();
hashtable.put(englishWord, chineseWord);
}
// 新增方法,将键值对进行反转
HashMap<String,String> reversedHashtable = new HashMap<String,String>();
for (String key : hashtable.keySet()) {
String value = hashtable.get(key);
reversedHashtable.put(value, key);
}
hashtable.putAll(reversedHashtable);
} catch(Exception e) {}
}
public void setView(WindowWord view) {
this.view = view;
}
public void actionPerformed(ActionEvent e) {
String inputWord = view.inputText.getText();
if (hashtable.containsKey(inputWord)) {
String outputWord = hashtable.get(inputWord);
view.showText.setText(outputWord);
} else {
// 新增判断,如果输入的是中文,则进行翻译
String chineseWord = inputWord;
for (String key : hashtable.keySet()) {
String value = hashtable.get(key);
if (value.equals(chineseWord)) {
view.showText.setText(key);
return;
}
}
view.showText.setText("没有此单词");
}
}
}
```
需要注意的是,此代码只能进行简单的单词翻译,无法处理词组、句子等复杂情况。
阅读全文