简体   繁体   中英

How to access variable from main, java

I am having trouble trying to make a HashMap accessible to other methods in the class that it's in.

Here is basically what I am trying to do,

class object
    method main
        this.test=9
    method fire
        output this.test

Here is the real code

import java.util.*;
import java.lang.String;
import java.util.HashMap;

public class problem {
    public HashMap dict;

    public problem() {
        HashMap<String, String[]> dict = new HashMap<String, String[]>();

        // put everything into hashmap
        String[] items = { "toys", "sun" };
        dict.put("animal", items);
        String[] items_2 = { "fun", "games" };
        view.put("human", items_2);

        this.view = view;

        // start
        this.BeginM();
    }

    public void BeginM() {
        System.out.println(this.view.get("human")[0]); // should give "fun"
    }
}

I get this error at the output stage:

array required, but java.lang.Object found

You know what? I've had one of those days where no matter how hard you try nothing quite ends up working right so, in order to have something actually working right, I'm going to fix up your code!

I sometimes see people post total rewrites of strange questions here and I've always wondered why!? Now I know, it's to compensate for having a day where one of your virtual machines goes belly up for no reason, you've got a bug that eludes reproduction until the moment you look away and your dog forgot his housetraining spontaneously.

Anyway, you need to figure out whether you want that variable to be called dict or view . Pick one, but you'll need to stick with it. I don't really care, but I'm using dict here. If you prefer the other, hey, it's your code, do what you like! But don't use both, that'll get confusing.

Your problem is that in your field, you're just using HashMap . Use the fancy well-typed stuff, or cast. Otherwise, HashMap just holds Object s. And an Object isn't a String[] . So you either need to cast the results of get() to a String[] , or you can just forget about all that and use the fancy well-typed stuff (sometimes we call that "generics"). I'm going to use the fancy well-typed stuff ( HashMap<String, String[]> ), but like I said - it's your code, cast if you want to!

Anyway, that gets us to:

public class problem
{
    HashMap<String, String[]> dict;

    public problem()
    {
        HashMap<String, String[]> dict = new HashMap<String, String[]>();

        // put everything into hashmap
        String[] items =
        {
            "toys", "sun"
        };
        dict.put("animal", items);
        String[] items_2 =
        {
            "fun", "games"
        };
        dict.put("human", items_2);

        this.dict = dict;

        // start
        this.BeginM();
    }

    public void BeginM()
    {
        System.out.println(this.dict.get("human")[0]); // should give "fun"
    }
}

See my line 3? By declaring that field dict as a HashMap<String, String[]> , now BeginM() knows what kind of objects it holds and you won't get that error any more.

Although I'd take it a step further and make it a bit more concise and a bit less error prone:

public class Problem
{
    private final HashMap<String, String[]> dict;

    public void Problem()
    {
        dict = new HashMap<String, String[]>();

        dict.put("animal", new String[] { "toys, "sun" });
        dict.put("human", new String[] { "fun", "games" });

        BeginM();
    }

    public void BeginM()
    {
        System.out.println(dict.get("human")[0]);
    }
}

So what did I do there? Well, first I capitalized Problem . It's sort of convention to have class names that start with a capital letter. Not mandatory, of course, but it's nice to have, especially when you're working with other developers. Case in point: I thought your constructor for problem was a method that lacked a return value! Also, I made dict final and private, this is so that you don't accidentally overwrite that field later. And I made it private, which is good design. If somebody else needs to get at it, we can give them an accessor method. Finally, I got rid of this. , because I don't really like it - but, hey, still your code, put it back if you want!

I believe this.view.get("human") returns a String, not an array. You need to use this.view.get("human").charAt(0) instead of this.view.get("human")[0] , since Java Strings can't be indexed like arrays.

Change: (BTW, missing from your example)

Map view = new HashMap<String,String[])

to;

Map<String,String[]> view = new HashMap<String,String[])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM