Hey I’m creating a password validation program that requires the program to check for digits, letters, and the length of the password, then the program compares the two passwords to see if they match. Everything works fine, but when the error message displays, it shows multiple message boxes. I know this has something to do with the for loop, but I’m still a beginner and I have no idea how to fix it.
Here’s my code:
import javax.swing.JOptionPane;
public class Passwords
{
public static void main(String[] args)
{
String passOne, passTwo;
passOne = JOptionPane.showInputDialog(null, "Please enter a password");
passTwo = JOptionPane.showInputDialog(null, "Please re-enter your password");
//Loop for each digit in password
for(int x = 0; x < passOne.length(); x++)
{
//Testing for a digit
if(Character.isDigit(passOne.charAt(x)))
{
//Testing for a letter
if(Character.isLetter(passOne.charAt(x)))
{
//Testing length 6-10 chars
if(passOne.length() <= 10 && passOne.length() >= 6)
{
//comparing two passwords
if(passOne.equals(passTwo))
{
JOptionPane.showMessageDialog(null, "Contratulations, you have a new password!");
}
//If passwords don't match
else
{
JOptionPane.showMessageDialog(null, "Passwords do not match, please try again.");
}
}
//If length is wrong
else
{
JOptionPane.showMessageDialog(null, "Password must be between 6 and 10 characters long.");
}
}
//If no letter
else
{
JOptionPane.showMessageDialog(null, "Password must contain at least one letter.");
}
}
//If no digit
else
{
JOptionPane.showMessageDialog(null, "Password must contain at least one digit.");
}
}
}
}
It’s because you are showing the error for each character that makes it fail validation.
The gist of the solution is you have to break out of your loop as soon as you find an error. Then if you did indeed have an error (which you recorded before breaking out), you display it.
I didn’t actually run it, but it should be closer, try this: