-1

When I try to login with redbull as username and pass123 as password it doesnt show the access granted message instead goes to else statement and show the access denied message

    Label usernameLb = new Label("Username:");
    GridPane.setConstraints(usernameLb, 0, 0);

    TextField usernameTf = new TextField();
    usernameTf.setPromptText("Username");
    GridPane.setConstraints(usernameTf , 1, 0);

    Label passLb = new Label("Password:");
    GridPane.setConstraints(passLb, 0, 1);

    TextField passTf = new TextField();
    passTf.setPromptText("Password");
    GridPane.setConstraints(passTf, 1, 1);

    Button loginBtn = new Button("Login");
    loginBtn.setOnAction(e -> {

        String username = usernameTf.getText();
        String password = passTf.getText();

        if (username == "redbull" && password == "pass123"){

            System.out.println(username + "\n" + password);
            JOptionPane.showMessageDialog(null, 
                    "Access Granted", " ", JOptionPane.PLAIN_MESSAGE);

        } else {

            System.out.println(username + "\n" + password);
            JOptionPane.showMessageDialog(null, 
                    "Access Denied", " ", JOptionPane.PLAIN_MESSAGE);
        }
    });

    GridPane.setConstraints(loginBtn, 1, 2);

    gridPane.getChildren().addAll(usernameLb, 
    usernameTf, passLb, passTf, loginBtn);

    Scene scene1 = new Scene(gridPane, 300, 200);
    window.setScene(scene1);
    window.show();

}
Ahmad
  • 3
  • 2
  • 1
    You cannot reliably compare strings using `==`. Use `if(username.equals("redbull")` instead... – Zephyr Jun 23 '18 at 05:05

1 Answers1

-2

Use .equals() when comparing the value of two Strings.

(username.equals("redbull") && password.equals("pass123"))

Nick Silvestri
  • 191
  • 1
  • 15