嘿,我正在创建一个密码验证程序,该程序要求程序检查密码的数字、字母和长度,然后程序比较两个密码以查看它们是否匹配。一切正常,但是当显示错误消息时,它会显示多个消息框。我知道这与 for 循环有关,但我仍然是初学者,我不知道如何解决它。
这是我的代码:
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.");
}
}
}
}
最佳答案
您的代码存在几个问题
您正在迭代密码的字符,但在每次迭代中您都会检查整个密码的长度。您只需在循环之外执行一次。这也适用于检查
passOne
和passTwo
的相等性
“外包”代码来检查数字/字符,如下所示:
static boolean containsOnlyDigitsOrLetters(String s) { for(int i = 0; i < s.length; i++) { if(!(Character.isLetter(s.charAt(i)) || Character.isDigit [...])) { // if the current character is neither a letter nor a digit return false; } } // all characters are either digits or letters return true; }
我特意发布了“仅包含数字和字母”的代码,而不是“至少一位数字”/“至少一个字母”顺便说一句;) 然后,您可以使代码更具可读性,就像这样的伪代码:
if password's length is not okay: display 'at least 6, at max 10' else if passwords do not match: [...] else if password does not contain a letter: // if(!containsAtLeastOneLetter(passOne)) display 'use at least one letter' [....]
关于java - For循环在java中显示多个消息框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610694/