0

I started learning Java recently so I decided to make a simple sign up/log in form.

private JTextField username;
private JPasswordField password;
private JButton check;
private JButton addToDb;
ArrayList<String> dbUser = new ArrayList<String>();
ArrayList<String> dbPassword = new ArrayList<String>();

public trial(){
    super("Title");
    setLayout(new FlowLayout());

    username = new JTextField("",10);
    password = new JPasswordField("",10);
    check = new JButton("Login");
    addToDb = new JButton("Sign Up");
    add(username);
    add(password);
    add(check);
    add(addToDb);

    addToDb.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){
                    if(!username.getText().isEmpty()
                        && !password.getText().isEmpty()){

                        dbUser.add(username.getText());
                        dbPassword.add(password.getText());
                        username.setText("");
                        password.setText("");
                        System.out.println(dbUser + "/" + dbPassword);

                    }else{

                        System.out.println("Please fill the fields and try again!");
                    }
                }
            }               
    );

    check.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent event){

                    for(int i=0; i<dbUser.size();i++){

                        if(username.getText() == dbUser.get(i) && password.getText()== dbPassword.get(i)){
                            JOptionPane.showMessageDialog(null, "Access Granted!");
                        }else{
                            JOptionPane.showMessageDialog(null, "Access Denied!");
                        }                       
                    break;                          
                    }
                }
            }
    );                      
  }
}

As you can see, I've made two text fields (username and password), two buttons, one that stores the values in two different arraylists (I tried with a HashMap but that didn't work either). And one that compares the values in the arrays to the values in the text fields. The problem is that when I use the login button, it always says access denied. Any ideas how to fix this?

Adri
  • 3
  • 3
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of `if (fu == "bar") {` do `if ("bar".equals(fu)) {` or `if ("bar".equalsIgnoreCase(fu)) {` – Hovercraft Full Of Eels Dec 26 '15 at 17:51
  • Also, your compiler should complain when you try to call `getText()` on your JPassword field -- listen to that complaint and in the interests of code security and safe coding don't call that method. Instead work with the char array that is returned by `getPassword()`. – Hovercraft Full Of Eels Dec 26 '15 at 17:55
  • @Hovercraft Full Of Eels To mark this question as a duplicate seems strange to me: Of course it boils down to comparing strings with equals() instead of == but the author of the question was not aware of this fact since he/she is learning java. It seems backward to me because if the author would have been aware of this fact he/she wouldn't have done this mistake. ? – morpheus05 Dec 26 '15 at 17:55
  • 1
    @morpheus05 If we don't mark these questions as Duplicate, then SO will be full of such question. String comparison are very mistakes/confusion which user have. Marking them as Duplicate helps maintain the quality of SO. – YoungHobbit Dec 26 '15 at 17:59
  • 1
    @morpheus05: I think that you seriously misunderstand what it means to mark the question as a duplicate. It in no way is meant as a punishment to the original poster or his question -- rather this is done via a down-vote (and you can easily see that I did not down-vote the question). All it means is that yes, this question has been asked before, and that to learn more about the issue and to solve it, read the linked questions and their answers, answers which are much better than the ones provided here. – Hovercraft Full Of Eels Dec 26 '15 at 17:59
  • 1
    @morpheus05: the real question is, does this site really need yet another String == vs. equals question or another NullPointerException? Will new answers really provide more or better information than has been provided previously? The answer I think is obviously, no. – Hovercraft Full Of Eels Dec 26 '15 at 18:01
  • Hmm, this means that in SO you should only ask general questions no one has asked before and not about specific problems you have in your code? I ask this way because I see a lot of questions of beginners closed and marked as duplicate directing them to general answers but with no link, hint or tips why his particular problem is based on a general problem? From authso PoV his code is not working but he/she fails to understand why, should we not point that out? This is meant as a genuine question and not an insult to any one. But maybe meta is better place to ask this question... – morpheus05 Dec 26 '15 at 18:04
  • @morpheus05: This would probably be best discussed on meta, and in fact it has been discussed many times on that site, but I think that we all can agree that there are some questions that are so common, that are so obviously duplicates, that they should be closed quickly and likely deleted. These include this current topic, the NPE topic that I mentioned above, and the floating point precision issue. The other not-so-obvious duplicates can all be taken on a case by case basis, but the overall utility of the site should be maintained and maximized. ... – Hovercraft Full Of Eels Dec 26 '15 at 18:10
  • @morpheus05: myself, I usually try to leave a comment when closing a question as a duplicate so that the OP can see something for quick reference, as I have done for this question (please see the first comment above). – Hovercraft Full Of Eels Dec 26 '15 at 18:10
  • @morpheus05: for some interesting meta discussions on dups, I invite you to look at these links: [1](http://meta.stackoverflow.com/questions/252009/should-there-be-a-deterrent-for-answering-obvious-duplicate-questions), [2](http://meta.stackoverflow.com/questions/265165/rewarding-overzealous-users-for-answering-duplicate-questions-is-undermining-the) and [3](http://meta.stackoverflow.com/questions/297853/are-we-too-preoccupied-with-easy-questions?lq=1). – Hovercraft Full Of Eels Dec 26 '15 at 18:12
  • @Hovercraft Full Of Eels Thanks for the links & your time – morpheus05 Dec 26 '15 at 18:32
  • @morpheus05: Your welcome. If you feel that your views differ, or even if they don't but you want to contribute to improving this site, please get involved and add your views to the meta site discussions. – Hovercraft Full Of Eels Dec 26 '15 at 18:34

2 Answers2

0

If you want to compare Strings use equals method, == will compare addresses

So change

if(username.getText() == dbUser.get(i) && password.getText()== dbPassword.get(i))

to

if(username.getText().equals(dbUser.get(i)) && password.getText().equals(dbPassword.get(i)))
shjeff
  • 405
  • 4
  • 17
  • 1
    Java does not have addresses, they are called `reference`. `==` compares the reference hold by the object. – YoungHobbit Dec 26 '15 at 17:50
  • I agree with @YoungHobbit. And regardless, the question is so common and has been asked and answered so many times that it shouldn't have even been answered but rather closed as a duplicate, something I did, but only after 2 answers slipped through. – Hovercraft Full Of Eels Dec 26 '15 at 17:53
  • I'm sorry, I thought the problem was related to my arraylists rather than my operators. The reason is that I tried a few different methods to build my 'if statement' with no success. It looks like I didn't try the most obvious one. – Adri Dec 26 '15 at 19:18
0

In java Strings are compared with equals and not ==. The reason is, strings are objects and not primitives. See What is the difference between == vs equals() in Java? for more information about == and equals()

So the if expression is wrong:

username.getText().equals(dbUser.get(i)) && password.getText().equals( dbPassword.get(i))
Community
  • 1
  • 1
morpheus05
  • 4,772
  • 2
  • 32
  • 47