how would I edit this to be a class that verifies the password but is demonstrat
ID: 3715915 • Letter: H
Question
how would I edit this to be a class that verifies the password but is demonstrated in a separate program?
import java.util.Scanner;
public class PasswordVerify
{
public static void main(String[] args)
{
String input;
boolean hasUpper = false;
boolean hasLower = false;
boolean hasDigit = false;
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter a password: ");
input = keyboard.nextLine();
int passLength = input.length();
for (int i=0; i < passLength; i++)
{
char c = input.charAt(i);
if (Character.isUpperCase(c))
hasUpper = true;
else if (Character.isLowerCase(c))
hasLower = true;
else if (Character.isDigit(c))
hasDigit = true;
}
if (hasUpper && hasLower && hasDigit && (passLength >= 6))
{
System.out.println("Password is correctly formatted");
}
else
{
System.out.println("Password is not correct");
}
}
}
Explanation / Answer
/**Java programt that prompts user to
* enter password and check if the password
* is valid then print password is correct
* otherwise password is incorrect*/
//PasswordVerify.java
import java.util.Scanner;
public class PasswordVerify
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter a password: ");
input = keyboard.nextLine();
int passLength = input.length();
//Create an instance of Passwrod class with input string
Password passwrd=new Password(input);
//calling isValid method
if(passwrd.isValid())
System.out.println("Password is correctly formatted");
else
System.out.println("Password is not correct");
}
}
--------------------------------------------------------------------------------------------
//Password.java
public class Password
{
private String passCode;
//constructor that takes user input password
public Password(String input) {
passCode=input;
}
/**Returns true if the passcode is valid
* otherwise returns false*/
public boolean isValid()
{
boolean hasUpper = false;
boolean hasLower = false;
boolean hasDigit = false;
for (int i=0; i < passCode.length(); i++)
{
char c = passCode.charAt(i);
if (Character.isUpperCase(c))
hasUpper = true;
else if (Character.isLowerCase(c))
hasLower = true;
else if (Character.isDigit(c))
hasDigit = true;
}
if (hasUpper && hasLower && hasDigit && (passCode.length() >= 6))
return true;
else
return false;
}
}
--------------------------------------------------------------------------------------------
Sample Output:
Enter a password: 12ABab
Password is correctly formatted
sample run2:
Enter a password: 1234
Password is not correct
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.