Question

I am creating a dictionary application for a small assignment, these were, unfortunately, given out by random and I have simply pulled one that I have no idea how to implement.

I would like to hear your suggestions for taking user input and using that to look through the HashMap (is this possible?) to provide a definition.

Additionally (sorry), it has to be bilingual, could I simply have all the words in both languages in one HashMap and have a way to search through both?

I am really out of my league here, any help is appreciated.

import java.util.HashMap;
import java.util.Map;
import java.io.*;



public class Dictionary {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<String, String>();

        String s1 = getInput("Enter a word to define: ");



        map.put ("Abduction","A carrying away of a person against his will or illegally.");

        map.put ("Ache","To be in pain or distress.");

        map.put ("Befriend","To be a friend to, especially when in need.");

        map.put ("Bilingual","Speaking two languages.");

        map.put ("Comical","Something funny.");

        map.put ("Comprehensive","Large in scope or content.");

        map.put ("Deplete","To reduce or lessen, as by use, exhaustion or waste.");

        map.put ("Detest","To dislike or hate with intensity.");


    }


        private static String getInput(String prompt) {
            BufferedReader stdin = new BufferedReader(
                    new InputStreamReader(System.in));

            System.out.print(prompt);
            System.out.flush();

            try {
                return stdin.readLine();
            } catch (Exception e) {
                return "Error: " + e.getMessage();

            }
        }
    }
Was it helpful?

Solution

You've entirely missed the point of a HashMap if you're attempting to search through it. A HashMap is designed to subvert the need to search, by using the value as the key.

if(map.containsKey(userInput))
{
    return map.get(userInput);
}

This is what is meant by HashMap having an O(1) complexity when searching. You only ever need to iterate or recurse once.

Additionally (sorry), it has to be bilingual, could I simply have all the words in both languages in one HashMap and have a way to search through both?

Yes. Just add new entries to the HashMap.

map.put("Hello", "A greeting");
map.put("Hola", "Una greetingo"); // Forgive my slightly racist Spanish.

Extra (In your case Necessary) Reading

  • Read up on the HashMap. You need to learn some basic stuff about the object. You're out of your depth because you haven't spent the appropriate time learning about the problem.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top