-2

so i am learning how to use the HashMap object. My question is, if I use the scanner object to ask a user for a String and I save that to a String variable. How can I take that String and "compare" it to my HashMap.

For example if a user inputs "abc".

My HashMap has ("a","abra") ("b","blastoise") ("c","charizard")

I want to print to System.out.println the result -- abra blastoise charizard instead of abc.

I will share my code that i have now but i am stuck with the next step and i hope that i am being clear with my question.

 public static void main(String[] args) { Scanner sc = new Scanner(System.in); String keyboard = ""; HashMap hm = new HashMap(); hm.put("A","Abra"); hm.put("B", "Blastoise"); hm.put("C", "Charizard"); hm.put("D", "Dewgong"); keyboard = sc.nextLine(); 

Thank you in advanced :)

2
  • @JBNizet I understand why you thought it was duplicate, but i am not simply asking for the iterating process of a String. I want to know how to take that string and convert it in my value part of the HashMap. What you have marked as a duplicate has nothing to do with HashMaps Commented Apr 13, 2018 at 19:07
  • 1
    with String value = hashMap.get(key). That's basically the whole point of a HashMap: get a value associated to a key. Please, please read the javadoc, and read the collections tutorial. Commented Apr 13, 2018 at 19:09

1 Answer 1

1

You can use chars as the key of your Map such put('a', "Abra") then you compare each char.

char[] str = string.toLowerCase().toCharArray(); for(char c : str) System.out.println(map.get(c)); 

Also note that 'A' is different from 'a', you need to handle such case the best one would calling toLowerCase() in the string before getCharArray().

Sign up to request clarification or add additional context in comments.

6 Comments

@marco This makes sense i appriciate it! My question is the string.getCharArray(); part, netbeans doesn't have getCharArray existing inside of String
@GianNobilione that is no "Netbeans" thing, but a Java-thing: String#toCharArray()
@Marco ahh ok now it compiles, however i get null as the results, but this was definitely a good starting point
@Turing85 That might be a bit too advanced for me, but thank you :)
@GianNobilione replace 'string' by the one you read from Scanner and use the map you have
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.