I am trying to make a program that tests whether or not a password is valid or invalid. After the password is submitted, I would like to give the user a choice to re-run the program(by responding 'y'). Everything works in my code, except when y is pressed at the end, the program stops instead of starting over.
Any help would be greatly appreciated.
import java.util.Scanner;
import java.lang.*;
public class PasswordTest1
{
//Program main method
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String again = "y";
//Promt user to enter input
System.out.print("Enter a password: ");
String password = scan.nextLine();
//If-else to print whether the password is valid
if (checkPassword(password))
{
System.out.println("Valid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
} else {
System.out.println("Invalid Password");
System.out.println("Re-run Program (y/n)? ");
again = scan.next();
}
}
//Program new method
public static boolean checkPassword(String password) {
String again = "y";
while((again == "Y") || (again == "y")){
boolean checkPassword = true;
{
//Make sure password is at least 7 digits
if (password.length() < 8) {
checkPassword = false;
}
else {
//A password has at least 1 digit
int numberOfDigit = 0;
for (int i = 0; i < password.length(); i++) {
if (isDigit(password.charAt(i))) {
if(isDigit(password.charAt(i))){
numberOfDigit++;
}
}
}
if (numberOfDigit < 1) {
checkPassword = false;
}
//Check for lower case
int numberOfLowerCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isLowerCase(password.charAt(i))) {
if(isLowerCase(password.charAt(i))){
numberOfLowerCase++;
}
}
}
if (numberOfLowerCase < 1) {
checkPassword = false;
}
//Check for upper case
int numberOfUpperCase = 0;
for (int i = 0; i < password.length(); i++) {
if (isUpperCase(password.charAt(i))) {
if(isUpperCase(password.charAt(i))){
numberOfUpperCase++;
}
}
}
if (numberOfUpperCase < 1) {
checkPassword = false;
}
//Check for Special Characters
int numberOfSpecialCharacters = 0;
String specialCharactersString = "!@#$%^&*()'+,-./:;<=>?[]_{}|";
for (int i = 0; i < password.length(); i++) {
char ch = password.charAt(i);
if(specialCharactersString.contains(Character.toString(ch))){
numberOfSpecialCharacters++;
}
}
if (numberOfSpecialCharacters < 1) {
checkPassword = false;
}
}
}
return checkPassword;
}
return true;
}
public static boolean isDigit(char ch) {
return (ch <= '9' && ch >= '0');
}
public static boolean isLowerCase (char ch) {
return (ch <= 'z' && ch >= 'a');
}
public static boolean isUpperCase (char ch) {
return (ch <= 'Z' && ch >= 'A');
}
}