Reputation: 182
I have 4 textboxes, 2 of them being password boxes (for the user to confirm their password).
Here's my code:
public void actionPerformed(ActionEvent arg0) {
String username = usernameField.getText();
String emailAddress = emailField.getText();
String password1 = passwordField1.getText();
String password2 = passwordField2.getText();
if (password1 != password2) {
[code here]
}
}
How can I make it so that if the passwords aren't equal it stops the rest of the code in that method from executing?
Upvotes: 0
Views: 119
Reputation: 17454
How to stop the rest of code in current method from executing in Java?
I would say there are 2 ways:
Let the program flow naturally to the end of the method:
public void actionPerformed(ActionEvent e){
if(password1.equals(password2)){
//Do all the things if password is correct
}
} //<-- If password is incorrect, point of execution will come to here
To exit a method before you reach the end of the method, you can use return
:
public void actionPerformed(ActionEvent e){
if(!password1.equals(password2)){
return;
}
else{
//Do all the things if password is correct
}
}
Upvotes: 2
Reputation: 106440
There is a significant problem before you can do this: you have to compare strings correctly. Then, you can decide what to do if they're false. Ultimately, using return
in a void
method is acceptable if you only want to return.
if (!password1.equals(password2)) {
// [code here]
}
However, the better approach would be to do a simple blanket check, and avoid the early return - if the passwords are valid, then do operations in the scope of that block. The fall-through case would exit the method early.
public void actionPerformed(ActionEvent arg0) {
String username = usernameField.getText();
String emailAddress = emailField.getText();
String password1 = passwordField1.getText();
String password2 = passwordField2.getText();
if (password1.equals(password2)) {
// code on success here
}
}
Upvotes: 3
Reputation: 5471
Never compare strings with boolean operators - Bad practice!
To solve your question just do this:
if (!password1.equals(password2)) {
return;
}
Upvotes: 2