Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Zman3359

Thread: why does this not return else and why is variable not used

  1. #1
    harland09 is offline Member
    Join Date
    Jun 2011
    Posts
    2
    Rep Power
    0

    Default why does this not return else and why is variable not used

    if someone could please help this a follow to my earlier question for the ok button if password is correct will change your panels background colour and tells you you have the correct password if not the panel would remain black and through up a error message however the else statement is not being returned so its as if the user has always passed help woul be very welcomed

    code for ok button

    private void OKButtonActionPerformed(java.awt.event.ActionEvent evt) {
    String password;
    String pass = txtPassword2.getText();
    password = "123";
    Boolean isMatch = false;
    isMatch = password.equals(pass);
    if (isMatch = true) {
    JOptionPane.showMessageDialog(controllingFrame,
    "Success! You typed the right password, the door is open.");
    jP1.setBackground(Color.red);
    }
    else{
    JOptionPane.showMessageDialog(controllingFrame,
    "Invalid password. Try again.",
    "Error Message",
    JOptionPane.ERROR_MESSAGE);

    }
    }

  2. #2
    Zman3359's Avatar
    Zman3359 is offline Member
    Join Date
    Jan 2011
    Posts
    42
    Rep Power
    0

    Default

    "if(isMatch = true)" This line should be "if(isMatch)" or "if(isMatch == true)". When you do what you have it is setting isMatch to true then evaluating the if statement. That is why it is always true and never enters the else.
    harland09 likes this.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    You made a mistake comparing boolean variables here
    Java Code:
    if(isMatch = true)
    Notice anything weird about it?

    Also, when testing a boolean variables condition it's better to use these approaches
    Java Code:
    boolean x = true
    if(x){}        //x == true
    else if(!x){} //x == false

Similar Threads

  1. Dynamic variable name based on other variable
    By nadissen in forum Eclipse
    Replies: 4
    Last Post: 05-06-2011, 07:22 PM
  2. Replies: 11
    Last Post: 07-07-2010, 07:02 AM
  3. return new variable -problem
    By Hevonen in forum New To Java
    Replies: 7
    Last Post: 12-08-2008, 07:07 AM
  4. Using int/int, 7/5 would return 1
    By zoe in forum New To Java
    Replies: 2
    Last Post: 12-02-2008, 12:25 PM
  5. if..else..return
    By mqdias in forum New To Java
    Replies: 1
    Last Post: 08-10-2007, 05:20 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •