-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 :)

  • @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 – Gian Nobilione Apr 13 '18 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. – JB Nizet Apr 13 '18 at 19:09

1 Answers1

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().

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
  • @marco This makes sense i appriciate it! My question is the string.getCharArray(); part, netbeans doesn't have getCharArray existing inside of String – Gian Nobilione Apr 13 '18 at 18:57
  • 1
    @GianNobilione that is no "Netbeans" thing, but a Java-thing: [`String#toCharArray()`](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#toCharArray--) – Turing85 Apr 13 '18 at 18:58
  • @Marco ahh ok now it compiles, however i get null as the results, but this was definitely a good starting point – Gian Nobilione Apr 13 '18 at 19:04
  • @Turing85 That might be a bit too advanced for me, but thank you :) – Gian Nobilione Apr 13 '18 at 19:04
  • @GianNobilione replace 'string' by the one you read from Scanner and use the map you have – Marcos Vasconcelos Apr 13 '18 at 21:10
  • @MarcosVasconcelos Yeah thats what i did, i changed string to keyboard and map to hm and no matter what i input i get null. Its bizarre. I logically understand what its doing and it makes total sense. – Gian Nobilione Apr 13 '18 at 21:15