从方法获取哈希图 [英] get Hashmap from Method

查看:113
本文介绍了从方法获取哈希图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,还没有学习如何创建2个单独的类并将它们组合在一起,因此,我最终将所有内容都弄乱了,您可以想象代码最终看起来是无法理解的,我计划稍后在我的课程中学习.但是,我需要一种可以与方法"一起使用的解决方案,这样我的代码才能看起来更简洁,并且如果我需要对其进行添加或修复,也就不会很麻烦.

I'm new to Java and haven't yet learned how to create 2 separate classes and combine them and so, I end up jumbling everything in the main and you can imagine how the code end up looking not understandable, which I plan to learn later on in my course. Yet I need a solution to work with 'Methods' so my code can look cleaner and if I need to add to it or repair it wouldn't be much of a hassle.

所以基本上,我的问题是我是否可以从主体使用Hashmap.get从方法中创建的哈希映射中获取信息:

So basically my question is whether I can use Hashmap.get from the main to get information from a hashmap that was created in a method:

static String createAccount(String username, String authpassword) {
    Map<String, String> newacc = new HashMap<String, String>();

}

上面是方法看起来"的样子,下面是主要方法:

This above is how the method 'would' look like and below the main method:

public static void main(String args[]) {
    newacc.get(username);

}

这是可能的,似乎我有此错误(我认为主要方法没有读取在方法中创建的hasmap.

Is this possible and it seems that I'm having this error (which I think that the main method is not reading the hasmap created in method.

error: cannot find symbol
    newacc.get(username);

先谢谢您!

推荐答案

createAccount()中创建的地图将分配给局部变量newacc.这意味着在方法完成后您将失去对它的引用.

The map you create in createAccount() is assigned to the local variable newacc. This means you lose the reference to it after the method finishes.

如果您想保留一张地图,以便在其中添加新帐户,可以将其设为班级的字段:

If you want to keep a map where you can add new accounts you could make it a field of your class:

class AccountManager {
    private static Map<String, String> accounts = new HashMap<>();

    static void createAccount(String username, String authpassword) {
        accounts.put(username, authpassword);
    }

    static String getAuthPassword(String username) {
        return accounts.get(username);
    }

    public static void main(String[] args) {
        // get the input from somewhere
        AccountManager.createAccount(username, authpassword);
        AccountManager.getAuthPassword(username);
    }
}

这篇关于从方法获取哈希图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆