这是一道比较简单的词典管理的题目,实现查词,添加词语,添加同义词,查同义词的功能,当然啦,用到Map(映射)!
1.这是JavaAPI文档中对方法next()的简单介绍,我遇到的问题就是抛出了NoSuchElementException异常;
2.解决方法:
在45行,46行程序执行的时候报错了,我的29行
if((map.get(word).equals(map.get(string)))&&(word!=string))原来的写法是
if((map.get(word).equals(map.get(it.next())))&&(word!=it.next())),后来在28行添上了String string = (String)it.next();程序可以运行了,没有报错;
package priv.xiaomin.dictionary;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class DictionaryManeger {
Map<String,String> map = new HashMap<String, String>();
public void findWord(String word){
Set<String>key = map.keySet();
for(Iterator it = key.iterator();it.hasNext();){
if (word.equals(it.next()) ){
System.out.println("该词的意思是:" + map.get(word));
}
}
}
public void addWordExplain(String word,String explain){
map.put(word, explain);
}
public void addSameExplainWord(String word1,String word2,String explain){
map.put(word1, explain);
map.put(word2, explain);
}
public void findSameWord(String word){
Set<String>key = map.keySet();
int count = 0;
for(Iterator it = key.iterator();it.hasNext();){
String string = (String)it.next();
if((map.get(word).equals(map.get(string)))&&(word!=string)){
System.out.println(word+"的同义词是"+string);
count++;
}
}
if(count == 0){
System.out.println("该词"+word+"没有同义词");
}
}
public static void main(String[] args) {
DictionaryManeger manager = new DictionaryManeger();
manager.addWordExplain("mother", "parent");
manager.addWordExplain("father", "family");
manager.addWordExplain("brother", "family");
manager.findWord("mother");
manager.findWord("father");
manager.findSameWord("mother");
manager.findSameWord("father");
manager.addSameExplainWord("cat", "dog", "animals");
manager.findWord("cat");
}
}
3.参考了一下别人的说法,循环中不能用两次(含)的next()。
欢迎大家对我的博文进行批评指正哦~希望能和大家共同学习共同进步!