【发布时间】:2016-10-14 22:40:38
【问题描述】:
我正在做一个项目,我将获得两个文件;一个是乱七八糟的词,另一个是真实的词。然后我需要按字母顺序打印出混乱的单词列表,旁边是匹配的真实单词。问题是每个混乱的单词可以有多个真实的单词。
例如:
猫猫
斑马
psot 停止后
我完成了程序,没有考虑每个混乱单词的多个单词,所以在我的 HashMap 中,我不得不将 更改为 >,但是在这样做之后我遇到了一些错误在 .get 和 .put 方法中。对于每个混乱的单词,如何为每个键存储多个单词?谢谢您的帮助。
我的代码如下:
import java.io.*;
import java.util.*;
public class Project5
{
public static void main (String[] args) throws Exception
{
BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) );
BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) );
HashMap<String, List<String>> dWordMap = new HashMap<String, List<String>>();
ArrayList<String> scrambled = new ArrayList<String>();
while (dictionaryList.ready())
{
String word = dictionaryList.readLine();
//throw in an if statement to account for multiple words
dWordMap.put(createKey(word), word);
}
dictionaryList.close();
ArrayList<String> scrambledList = new ArrayList<String>();
while (scrambleList.ready())
{
String scrambledWord = scrambleList.readLine();
scrambledList.add(scrambledWord);
}
scrambleList.close();
Collections.sort(scrambledList);
for (String words : scrambledList)
{
String dictionaryWord = dWordMap.get(createKey(words));
System.out.println(words + " " + dictionaryWord);
}
}
private static String createKey(String word)
{
char[] characterWord = word.toCharArray();
Arrays.sort(characterWord);
return new String(characterWord);
}
}
【问题讨论】:
-
因此,当您想从 Hashmap 编辑或获取值时,请确保您使用 List
作为值和 String 作为键,目前您正在尝试将 String 分配给您获得的内容从 .get() 返回 List 对象类型 -
当然
String与List<String>不同。你对什么感到困惑?