EDIT--VERSION
The first post was confusamagin. My assignment is to create a password prompt program. The password needs to be checked to see if it does have at least one digit and one letter in it. Also the password length must be between 6 - 10.
My problem is trying to figure out how see if a digit and letter exist the password. In the check password area I am not sure where to begin really. I am not sure how to see if it has a Letter and a Digit in one. I know how to do either or by using a for statement to count and check but all it does is check to see rather it contains all letters or all digits.
Below is what I have so far...
import java.util.Scanner;
class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//------ENTER A USERNAME
System.out.println("Welcome please enter your username and password.");
System.out.print("Username >>");
input.nextLine();
//------PASSWORD AUTHENTICATION BEGIN
String password = enterPassword();
while ( !checkPassword(password) ) {
System.out.println("Password must be 6 - 10 characters long!");
password = enterPassword();
}
//------PASSWORD VERIFY
String passwordverify = enterPassword();
while (!password.equals(passwordverify)){
System.out.println("ERROR - Passwords DO NOT MATCH Re-Enter Passwords Again");
password = enterPassword();
}
//------ACCEPT PASSWORD
System.out.println("Username and Password Accepted!");
}
//--ENTER PASSWORD STATEMENT
public static String enterPassword(){
String password;
Scanner input = new Scanner(System.in);
System.out.print("Password >>");
password = input.nextLine();
return password;
}
//--BOOLEAN CHECK PW
public static boolean checkPassword(String password){
int length;
length = password.length();
if (length < 6 || length > 11){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(i)))
return false;
}
return true;
}
}
public static boolean checkPasswordLetter(String password){
for (int i = 0; i < password.length();){
if (!Character.isLetter(password.charAt(i))){
return false;
}
}
return true;
}
Here you didn't increment variable i , need in for i++ or your loop is going forever if is not letter, same and in checkPasswordDigit
checkPasswordLetter and checkPasswordDigit will only return true if ALL chars are letters/digits respectively. Is this what you meant?
First off... It's not that Java is not looping or checking Boolean. Java is doing what you are telling it to do.
Now, what you want to do is different than what you are doing.
What you need to do is something like:
public static void main(String[] args) {
// ...
String password = enterPassword();
while ( !isPasswordValid(password) ) {
password = enterPassword();
}
System.out.println("Username and Password Accepted!");
}
public static boolean isPasswordValid(String password) {
// return true if and only if password:
// 1. has 6-10 characters
// 2. contains at least one digit
// 3. contains at least one character
// print messages accordingly
}
There are two things wrong.
Your letter checking is failing on the first non-letter. Same thing happening with your digit checking. You only want to reject if every character is a non-letter, for example. So logic error.
You have three loops. Bad idea, because if you pass the length check once, it is never going to be checked again. Consider what would happen if someone entered: 12345678. Length ok, but no letter. Ok, now enter: a1. Length not checked again.
import java.util.Scanner;
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class CheckingPassword
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 9) {
return false;
}
else {
char c = 0 ;
int count=0;
System.out.println(password.length());
for (int i = 0;i<=password.length()-1; i++)
{
c = password.charAt(i);
System.out.println(c);
if (!Character.isLetterOrDigit(c))
{
return false;
}
else if (Character.isDigit(c))
{
count++;
if(count==3)
{
return false;
}
}
}
return true;
}
}
}
import java.util.Scanner;
public class password{
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a password ") ;
String s = input.nextLine();
if(isValid(s))
System.out.println(s + " is a valid password");
else
System.out.println(s + " is not a valid password");
}
public static boolean isValid(String s )
{
int i = 0,j=0;
if(s.length()>=8)
{
for(i=0;i<s.length();i++)
{
//if(Charcter.isLetter(s.charAt(i))||Digit.isLetter(s.charAt(i)))
if (Character.isLetterOrDigit(s.charAt(i)))
{
if(Character.isDigit(s.charAt(i)))
j++;
}
}
}
else
return false;
if(j>=2)
return true;
return false;
} }
Related
The user should give a string, where we should check if all characters are numbers.
If all are digits, we will get one message that the password is with digits and move on with the program. If any of them (or all) is not a digit, then the user should enter password again.
(E.g. 465486 is acceptable. hell3429384 or sfdkjsfkj is not acceptable)
Apparently, my code is not working correctly, since whether I give a number or a letter to the password, I get the same result.
Am I looping something wrong, or am I using the isDigit method wrong?
import java.util.*;
public class Password {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit;
for(int i = 0; i < length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (Character.isDigit(i)) { /*checking if each character is digit*/
isadigit = true; /* if it is, give the value to isadigit true*/
System.out.println("PASSWORD is w digits");
}
else {
System.out.println("PASSWORD w/out digits");
passn.nextLine();
}
}
}
}
If you can use java-8 there is one-liner:
pass.chars().allMatch(Character::isDigit)
You are not checking each character, but each index value.
Change
if(Character.isDigit(i))
to
if(Character.isDigit(character))
Also: you don't break out of the loop when you encounter a non-digit...
A side note if you are on Android:
You can use TextUtils.isDigitsOnly() directly, e.g.
TextUtils.isDigitsOnly(myString)
And just in case, an empty string is digit only because it doesn't contain any non-digit; also this method is not null-tolerant.
To be honest: You could write code like you did. But it would be better to use a regular expression on that. You want to know, if a certain String only contains digits. Here is the code:
String foo = "My_pwd_is_wrong_123!";
String bar = "123";
boolean foo_ok = foo.matches("^[0-9]*$") // Will be "false"
boolean bar_ok = bar.matches("^[0-9]*$") // Will be "true"
Ok, in that case: Your Problem is, that you continue your loop after identifiyng a non-digit in one Password. You need to BREAK your loop, as soon as you find a non-digit in the pwd:
public class TEST {
public static void main(String[] args) {
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
int length = pass.length();
boolean isadigit = true;
for(int i = 0; i<length; i++) { /*looping each character one by one*/
char character= pass.charAt(i);
if (!Character.isDigit(character)) { /*checking if current character is digit*/
isadigit = false; /* if it is not, give the value to isadigit false*/
break;
}
}
if(isadigit)
System.out.println("PASSWORD is w digits");
else
System.out.println("PASSWORD w/out digits");
}
}
Please see this sample implementation
boolean isDigit = false;
for (int i = 0; i < length; i++) {
char character = pass.charAt(i);
if (Character.isDigit(character)) {
isDigit = true;
} else {
passn.nextLine();
}
}
if (isDigit) {
System.out.println("PASSWORD is w digits");
} else {
System.out.println("PASSWORD w/out digits");
}
In Kotlin, you can use
text.all { it.isDigit() }
try to parse the string to Integer.
catch the exception
Scanner passn = new Scanner(System.in);
System.out.println("Give password: ");
String pass = passn.nextLine(); /* user enters password*/
try
{
Integer.parseInt(pass);
System.out.println("Digital password!");
}
catch(NumberFormatException nfe){
System.out.println("without digit password!");
}
I am new to Java and am creating a project for class that basically asks the user to input a string, and then tests the string and prints whether or not it is a palindrome (the same forwards as backwards... i.e. mom or dad or racecar)
I have gotten the code to work, however i have a loop setup to rerun the program or quit at the end. My problem is that when you rerun the program and enter another String input then it's adding it to the original string.
How can I reset or delete the String input each time so that it starts fresh?
Thank you for any help! Also please note, there may be better or faster ways to accomplish what I have done here but my knowledge of java is limited and I am just getting started, so I have used the knowledge that I have thus far learned. Thanks!!
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
Ok, figured it out thanks to your guys' help... also rewrote the code so that you can just keep entering new strings or type q to quit instead of the redo question at the end. Hopefully this is cleaner!
import java.util.Scanner;
public class Palindrome_Test {
public static void main(String[] args) {
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
int length; //length of word entered by user
boolean redo = true; // boolean to rerun program
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please enter a string, or type Q to quit: ");
input = scan.nextLine();
if (input.equalsIgnoreCase("q")) {
System.out.println("Goodbye!");
redo = false;
} else {
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
reverse = "";
}
} while (redo);
} //end main
} //end class
At the end of your while loop add reverse = "";
You'll notice that I moved the following -
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
Inside of the first loop. Although you could simply reset both variables at the end of the loop...
input = "";
reverse = "";
There is no need to (Although, they both work!). By dealing with the scope of the variable inside of the loop, it will essentially "refresh" each time the loop executes.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// String input = ""; // Word entered by user
// String reverse = ""; //Reverse of String input
String redoAnswer; // answer to rerun program
int length; //length of word entered by user
boolean test;
boolean redo; // boolean to rerun program
boolean exit; // boolean to validate exit/rerun
Scanner scan = new Scanner(System.in);
do {
redo = true;
exit = true;
String input = ""; // Word entered by user
String reverse = ""; //Reverse of String input
System.out.println("Please enter a string: ");
input = scan.nextLine();
length = input.length();
for (int i = length - 1; i >= 0; i--)
reverse = reverse + input.charAt(i);
if (input.equalsIgnoreCase(reverse)) {
System.out.println("Yes, this string is a palindrome!");
} else {
System.out.println("Sorry, this string is NOT a palindrome!");
}
do {
System.out.println("Please type r to restart or q to quit");
redoAnswer = scan.nextLine().trim().toLowerCase();
if (redoAnswer.equals("r")) {
exit = false;
redo = true;
continue;
} else if (redoAnswer.equals("q")) {
exit = false;
redo = false;
System.out.println("Goodbye!");
continue;
} else {
System.out.println("Sorry, I didn't catch that.");
continue;
}
} while (exit);
} while (redo);
} //end main
} //end class
I have been experimenting with trying to get the code below running WITHOUT using a break statement (but i can't figure it out)
import java.io.*;
import java.util.*;
public class Password
{
public static void main (String [] args)
{
final String PASSWORD = "Test";
for (int passAttempts = 0; passAttempts < 3; passAttempts++)
{
System.out.print("\nEnter Your Password: ");
Scanner input = new Scanner(System.in);
String inputPass = input.nextLine();
if (!(inputPass.equals(PASSWORD)))
{
System.out.println("\nWrong Password Try Again");
}
else
{
System.out.println("\nWelcome!");
break;
}
}
}
}
This is my alternative attempt of trying to use a switch statement to "catch" each iteration of the loop and perform an action, but I'm not sure why its endless loop:
import java.io.*;
import java.util.*;
public class Password2
{
public static void main (String [] args)
{
final String PASSWORD = "Test";
System.out.print("\nEnter Your Password: ");
Scanner input = new Scanner(System.in);
String inputPass = input.nextLine();
do
{
for(int passAttempts = 0; passAttempts < 3; passAttempts++)
{
switch(passAttempts)
{
case 0:
System.out.println("\nWrong password try again\t2 attempts remaining");
break;
case 1:
System.out.println("\nWrong password try again\t1 attempts remaining");
break;
case 2:
System.out.println("\nWrong password try again\t0 attempts remaining");
break;
default:
System.out.println("\nContact Help desk");
break;
}
}
}
while(!(inputPass.equals(PASSWORD)));
}
}
Where am I going wrong?
You can do it like this, alternatively instead of comparing password in while statement put a break statement below the if(password.equals(PASSWORD), but since you said you want to avoid it:
public static void main(String[] args)
{
final String PASSWORD = "Test";
Scanner sc = new Scanner(System.in);
int attempts = 3;
String password = "";
while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
{
System.out.print("Enter your password: ");
password = sc.nextLine();
if (password.equals(PASSWORD))
System.out.println("Welcome");
else
System.out.println("Incorrect. Number of attempts remaining: " + attempts);
}
}
Using flag without change your code:
import java.util.*;
public class Password {
public static void main(String[] args) {
final String PASSWORD = "Test";
boolean wrongPass = true;
for (int passAttempts = 0; passAttempts < 3 && wrongPass; passAttempts++) {
System.out.print("\nEnter Your Password: ");
Scanner input = new Scanner(System.in);
String inputPass = input.nextLine();
if (!(inputPass.equals(PASSWORD))) {
System.out.println("\nWrong Password Try Again");
} else {
System.out.println("\nWelcome!");
wrongPass = false;
}
}
}
}
Ps: close your Scanner ;)
Just use a while and some flags:
final String PASSWORD = "Test";
final int MAX_PASS_ATTEMPS = 3;
boolean isLoggedIn = false;
int passAttemps = 0;
while (passAttemps < MAX_PASS_ATTEMPS && !isLoggedIn) {
System.out.print("\nEnter Your Password: ");
Scanner input = new Scanner(System.in);
String inputPass = input.nextLine();
if (!(inputPass.equals(PASSWORD))) {
System.out.println("\nWrong Password Try Again");
passAttemps++;
} else {
System.out.println("\nWelcome!");
isLoggedIn =true;
break;
}
}
I ended up with the following code in the end after some experimentation. The reasoning behind the programme...does the programme quit because the initialised boolean value of false is changed to true? Or is it because of the value changing in the for loop? Its works but its a bit tricky to explain why it functions hmm...
The for loop to my understanding behaves like so;
is 1 <= 3? Yes, so its True...and NOT false = TRUE
is 2 <= 3? Yes, so its True...and NOT false = TRUE
is 3 <= 3? Yes, so its True...and NOT false = TRUE
is 4 <= 3? No, so its false...and NOT false = false -> breaks loop
The part I'm confused on is declaring the boolean value as TRUE when the right password is entered, I don't grasp why it quits the programme...
Can someone clarify this for me with an equation perhaps?
Many thanks.
final String PASSWORD = "Test"; //sets constant password
final int MAX_PASS_ATTEMPTS = 3; //sets constant attempts
boolean adminLoggedIn = false;
for(int passAttempts = 1; passAttempts <= MAX_PASS_ATTEMPTS && !adminLoggedIn; passAttempts++) //compares and increments passAttempts
{
System.out.print("\nPassword: ");
Scanner input = new Scanner(System.in);
String inputPass = input.nextLine();
if (!(inputPass.equals(PASSWORD))) //If "Cisco" is not entered as password
{
System.out.println("\nERROR! Wrong Password! \t" + ((passAttempts - MAX_PASS_ATTEMPTS)*(-1)) + " Attempts Remaining"); //Deducts amount of attempts remaining
}
else
{
System.out.println("\nWelcome!");
adminLoggedIn = true; //breaks loop
}
}
Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}
Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}
Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}
Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.
I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}
Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);
Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}
You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.
I'm a student of CIS taking a Java class (hoping to become a programmer). Anyhow, I have an assignment to create a program that checks a password for validity. If the password is not valid, it is to print a message. If the password is valid, the user is to reinsert the password. If they both match, it is to print a message accepting. If they do not match, it is to print a message.
The password requirements are:
Must be at least 8 characters in length
Must contain one number
Must contain one letter
Must contain one special character
Cannot have 3 or more identical characters
Cannot contain spaces
Cannot start with ! or ?
I am using netbeans.
package pass1;
import java.util.Scanner;
public class Pass1 {
//Main method asks for pasword from user and calls upon methods to verify password requirements and password 1 and 2 match
public static void main(String[] args) {
//declare variables
String pass1;
String pass2;
boolean passvalid;
boolean passmatch;
//initialize new instance of scanner
Scanner kb = new Scanner(System.in);
//get password
System.out.println("Please input password. (Must be at least 8 characters, contain a number, letter, and special character");
pass1 = kb.nextLine();
//initialize instance of passisvalid to check password for requirements
passvalid = passisvalid(pass1);
//if pass is valid, allow user to reinsert password
if (passvalid){
System.out.println("Please reinsert password:");
pass2 = kb.nextLine();
//initialize instance of passismatch to check passwords match
passmatch = passismatch(pass1, pass2);
//if passwords do not match, print message
if (!passmatch)
{
System.out.println("Passwords do not match.");
}
//if passwords match, print message
else if (passmatch)
{
System.out.println("Password set.");
}
}
//if password is not valid, print message
else
{
System.out.println("Password is not valid:");
}
}
/*************************************************************************************/
//this method check that user inputted password meets requirements, and returns boolean value
public static boolean passisvalid(String password) {
//declare variables
boolean letter;
boolean digit;
boolean space;
boolean length;
boolean start1;
boolean start2;
boolean valid;
boolean special;
//initialize variables
valid=false;
letter=false;
digit=false;
space=false;
special=false;
length = false;
start1=false;
start2=false;
//initialize count
for(int i=0;i<password.length();i++)
{
char s=password.charAt(i);
//check for letter in password
if(Character.isLetter(s))
{
letter = true;
}
//check for number in password
if(Character.isDigit(s))
{
digit = true;
}
//check for spaces in password
if(Character.isSpaceChar(s))
{
space=true;
}
//check for special characters in password
if(!Character.isDigit(s) && !Character.isLetter(s))
{
special=true;
}
}
//check password length
if (password.length() > 8)
{
length=true;
}
//check password start with ? or !
else if (password.startsWith("?"))
{
start1=true;
}
else if (password.startsWith("!"))
{
start1=true;
}
//requirements of password for boolean true
if(letter && digit && special && length)
{
valid = true;
}
//return boolean false if detect start with ? or !, or spaces in password
if(start1||start2||space)
{
valid = false;
}
return valid;
}
/**********************************************************************************/
//this method checks that both user entered passwords match
public static boolean passismatch(String password1, String password2){
//declare variables
boolean match;
//initialize variables
match=false;
//compare password strings
if (password1.equals(password2))
{
match= true;
}
return match;
}
}
So I've been able to figure all except for making sure there are no consecutive repeating characters. I really don't even know where to begin with this. I've searched for hours on a few forums to try and find a solution and put it all together but without seeing an example or just something I can't figure it out for the life of me. Any help would be IMMENSELY appreciated.
You can get password to string array and compare each string with the next two string whether it has the same.
public static boolean hasConsecutiveCharacters(String pwd){
String[] letter = pwd.split(""); // here you get each letter in to a string array
for(int i=0; i<letter.length-2; i++){
if(letter[i].equals(letter[i+1]) && letter[i+1].equals(letter[i+2])){
return true; //return true as it has 3 consecutive same character
}
}
return false; //If you reach here that means there are no 3 consecutive characters therefore return false.
}
package filehandling;
import java.util.Scanner;
public class PasswordValidation {
public static void main(String[] args) {
String enterPassword ;
String reEnterPassword ;
boolean passValid ;
boolean isPassMatch ;
Scanner password = new Scanner(System.in);
System.out.println("Enter Your Password:");
System.out.println("(Must be at least 8 characters, contain a number, letter, and special character");
enterPassword = password.nextLine();
passValid = checkPassIsValid(enterPassword);
if(passValid) {
System.out.println("Re-Enter Your Password: ");
reEnterPassword = password.nextLine();
isPassMatch = checkPasswordMatching(enterPassword,reEnterPassword);
if(!isPassMatch)
System.out.println("Password do Not Match: ");
else if (isPassMatch)
System.out.println("Password Set.");
}
else
System.out.println("Password is Not Valid.");
}
private static boolean checkPassIsValid(String enterPassword) {
boolean length = false;
boolean letter = false;
boolean digit = false;
boolean space = false;
boolean startSpace = false;
boolean special = false;
boolean start1 = false;
boolean start2 = false;
boolean valid = false;
for(int i = 0; i < enterPassword.length(); i++) {
char c = enterPassword.charAt(i);
if(enterPassword.length() >= 8)
length = true;
if(Character.isDigit(c))
digit = true;
if(Character.isLetter(c))
letter = true;
if(Character.isSpaceChar(c))
space = true;
if( (!Character.isDigit(c)) && (!Character.isLetter(c)) )
special = true;
if(enterPassword.startsWith(" "))
startSpace = true;
else if(enterPassword.startsWith("?"))
start1 = true;
else if(enterPassword.startsWith("!"))
start2 = true;
if(letter && digit && special && length)
valid = true;
if(start1 || start2 || startSpace)
valid = false;
}
return valid;
}
private static boolean checkPasswordMatching(String enterPassword,String reEnterPassword) {
if(enterPassword.equals(reEnterPassword))
return true;
return false;
}
}