Search code examples
javaclasshashmapreturnreturn-value

How to use a HashMap returned from a method


Here I have a program which creates a HashMap within a method

import java.util.HashMap;


class Evan {
  public HashMap<String,Double> abilities_get() {
     HashMap<String,Double> abilities = new HashMap<String,Double>();
     abilities.put("stealth", 1.5);
     abilities.put("strength", 1.2);
     abilities.put("accuracy", 1.0);
     abilities.put("intelligence", 2.0);
     return abilities;
     
 }
 }

 public class Main {
 
    public static void main(String[] args) {
       Evan evan = new Evan();
       evan.abilities_get();
       abilities.get("stealth");
}
}

This program doesn't work due to the fact that in the main method "abilities" cannot be found. How can I make it so I can use my HashMap in the main function.


Solution

  • class Evan {
        public HashMap<String,Double> abilities_get() {
            HashMap<String,Double> abilities = new HashMap<String,Double>();
            abilities.put("stealth", 1.5);
            abilities.put("strength", 1.2);
            abilities.put("accuracy", 1.0);
            abilities.put("intelligence", 2.0);
            return abilities;
    
        }
    }
    
    class Main {
    
        public static void main(String[] args) {
            Evan evan = new Evan();
            evan.abilities_get();
            Double stealth = evan.abilities_get().get("stealth");
            System.out.println(stealth);
        }
    }
    

    Try it out