Reputation: 31
I want this program to sort jumbled words in alphabetical order, be compared to the dictionary, and be matched with dictionary words. I get it to print out the jumbles in alphabetical order but it will not print the dictionary words even though I have a print line.
public class i
{
public static void main(String[] args) throws Exception
{
if (args.length < 2 ) die("No dictionary");
BufferedReader dictionaryFile = new BufferedReader( new FileReader( args[0] ));
BufferedReader jumbleFile = new BufferedReader( new FileReader( args[1] ));
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> jumbleWords = new ArrayList<String>();
ArrayList<String> dictionaryWords = new ArrayList<String>();
while(dictionaryFile.ready())
{
String dictWord = dictionaryFile.readLine();
dictionaryWords.add(dictWord);
}
while(jumbleFile.ready())
{
String word = jumbleFile.readLine();
//String canWord = toCanonical(word);
jumbleWords.add(word);
map.put(word, new ArrayList<String>());
}
Collections.sort(jumbleWords);
for(String dictionaryWord : dictionaryWords)
{
String canDictWord = toCanonical(dictionaryWord);
if(map.containsValue(canDictWord))
{
ArrayList<String> listOfWords = map.get(canDictWord);
listOfWords.add(dictionaryWord);
}
}
ArrayList<String> keysList = new ArrayList(map.keySet());
Collections.sort(keysList);
for(String key : keysList)
{
System.out.print(key);
ArrayList<String> list = map.get(key);
Collections.sort(list);
for(String word : list)
{
if (toCanonical(key).equals(toCanonical(word)))
System.out.print(word + " ");
}
System.out.println();
}
}
private static void die( String errmsg )
{
System.out.println( "\nFATAL ERROR: " + errmsg + "\n" );
System.exit(0);
}
private static String toCanonical( String word )
{
char[] letters = word.toCharArray();
Arrays.sort(letters);
return new String(letters);
}
}
Upvotes: 0
Views: 66
Reputation: 97120
The values of your map are defined to be of type ArrayList<String>
, but in the code below, your trying to check whether it contains a regular String
.
if(map.containsValue(canDictWord)) {
// ...
}
This will always return false, so the reason your println
doesn't work is because the map's value ArrayList
s will always be empty.
It's difficult to figure out what you're actually trying to achieve, and the formatting (or lack thereof) of your code makes it even harder. You probably should try making a map with the dictionary words as keys, and the jumbled words as a list of values. Then you can use map.containsKey(toCanonical(jumbledWord))
and add the jumbled word to the list of values for that key.
Upvotes: 2