问题
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.
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);
}
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);
Thank you in advance!
回答1:
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);
}
}
回答2:
Your map newacc
will only be accessible within the createAccount
method and not to outside world as its scope is just within the method createAccount
and hence compilation error.
To resolve this, define newacc
as static and at class level. So just define Map outside the method like:
static Map<String, String> newacc = new HashMap<String, String>();
static String createAccount(String username, String authpassword) {
//access newacc here
}
And similarly you could access the same in main method directly.
回答3:
You won't be unable to access the newacc
variable from your main
method with your current code, because newacc
is scoped to the createAccount
method. You have two options, to define newacc
as a static field in your class and access the same instance from both methods (see answer from @SMA), or to return your account from the createAccount
method and capture it in main
. Like so:
Map<String, String> createAccount(String username, String password) {
Map<String, String> newacc = new HashMap<String, String>();
// do stuff with account
return newacc;
}
public static void main(String[] args) {
Map<String, String> newacc = createAccount("user", "pass");
newacc.get("username");
}
来源:https://stackoverflow.com/questions/29653463/get-hashmap-from-method