我查看了帖子,似乎无法找到与我的问题有关的答案。
我是java的初学者,必须制作一个用户输入密码的程序,我写的程序会检查以确保它符合要求:
在这样做之后,它应该询问用户是否想要输入另一个。这是我的代码:
public class Password
{
public static void main(String args[])
{
String SPECIAL_CHARACTERS = "!@#$%^&*()~`-=_+[]{}|:\";',./<>?";
int MIN_PASSWORD_LENGTH = 8;
Scanner scan = new Scanner(System.in);
String password;
char answer;
boolean continueRun = true;
while(continueRun)
{
password = "";
System.out.print("Enter a password: ");
password = scan.nextLine();
boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());
boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
boolean atLeast8 = password.length() >= 8;
if(!hasUppercase || !hasLowercase || !atLeast8 || !hasSpecial)
{
System.out.println("Entered password is:\t" + password);
System.out.println("Verdict:\tInvalid");
}
else
{
System.out.println("Entered password:\t" + password);
System.out.println("Verdict:\t\tValid");
}
System.out.print("Enter another password? Y/N: ");
answer = scan.next().charAt(0);
if (answer != 'Y')
{
continueRun = false;
}
}
}
}
我知道它可能不是最有效或最干净但它可以完成任务。我唯一的问题是每当用户决定继续输出时是这样的:
Enter another password? Y/N: Y
Enter a password: Entered password is:
Verdict: Invalid
Enter another password? Y/N:
如何让它重复,就像在程序初始阶段一样重复?
答案 0 :(得分:1)
只需将Scanner
放在循环中就像这样
while(continueRun)
{
Scanner scan = new Scanner(System.in);
...
这样程序将再次询问用户新密码。