如何在另一个方法中的方法中使用 HashMap 中的数据?

How can I use the data from a HashMap inside a method in another method?

所以我想在 Clicked 方法的 clickRegister 方法中使用添加到 HashMap 的数据。但据我所知,数据没有保存在方法之外。我假设那是因为它超出了范围? (我是编程新手,所以如果我错了请纠正我)。我怎样才能做到这一点?甚至有可能吗?

public class Controller {
    private HashMap<String, String> userList = new HashMap<String, String>();

    public void Clicked(ActionEvent actionEvent) throws IOException {
        String cpr = cprField.getText();
        String password = passwordField.getText();

        if (userList.containsKey(cpr) && userList.containsValue(password)){
            Stage stage1;
            Parent root1;
            stage1 = (Stage) loginButton.getScene().getWindow();
            root1 = FXMLLoader.load(getClass().getResource("home.fxml"));
            Scene scene = new Scene(root1);
            stage1.setScene(scene);
            stage1.show();
        } else {
            System.out.println("Wrong credentials");
        }
    }

    public void clickRegister(ActionEvent actionEvent) throws IOException {
        if (cprFieldReg.getText().equals("") && passwordFieldReg.getText().equals("")){
            System.out.println("Fill in blank fields");
        } else {
            String username = cprFieldReg.getText();
            String password = passwordFieldReg.getText();

            userList.put(username, password);
        }
    }
}

您只需要了解变量作用域如何用于变量声明。它在所有语言中都几乎相同。声明包括方法和构造函数参数声明和变量声明。

可能的范围包括:

  • 全局范围(程序的每个部分都可以访问声明)
  • Class 范围(可以从 class 的每个部分访问声明)
  • 实例范围(声明可从实例方法访问)
  • 方法作用域(方法内的任何地方都可以访问声明)
  • 局部作用域(可以在大括号内访问声明)

cpr 变量是在一个方法中声明的,因此它的范围仅限于该方法。如果将声明从 Click 方法中移出,移到 HashMap 声明的正下方,则可以从整个 class 访问该变量。我认为这可能是您在这种情况下所需要的。

这里有更多信息:https://en.wikibooks.org/wiki/Java_Programming/Scope