password validation using boolean - java

I have to write a code that check if a password is valid.
The problem is when the password pass every condition I don't get any answer if it's.
Right here you can see my code; I think I need to add something in my main function but I don't know what.
Is the else if statement not necessary?
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Please enter a password : ");
String passwordhere = in.nextLine();
List<String> errorList = new ArrayList<String>();
while (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
}
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
else if(digitCasePatten.matcher(passwordhere).find()&&passwordhere.length() < 8&&
specailCharPatten.matcher(passwordhere).find()&&lowerCasePatten.matcher(passwordhere).find()&&
UpperCasePatten.matcher(passwordhere).find()){
System.out.println("the pass is right");
flag=true;
}
return flag;
}
}

while (true) {
if (!isValid(passwordhere, errorList)) {
System.out.println("The password entered here is invalid");
for (String error : errorList) {
System.out.println(error);
}
System.out.print("Please enter a given password : ");
passwordhere = in.nextLine();
}
else {
System.out.println("Password is valid!");
break;
}
}

or change just your method isValid like this :
public static boolean isValid(String passwordhere, List<String> errorList) {
Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
Pattern lowerCasePatten = Pattern.compile("[a-z ]");
Pattern digitCasePatten = Pattern.compile("[0-9 ]");
errorList.clear();
boolean flag=true;
if (passwordhere.length() < 8) {
errorList.add("Password lenght must have alleast 8 character !!");
flag=false;
}
if (!specailCharPatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one specail character !");
flag=false;
}
if (!UpperCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one uppercase character !");
flag=false;
}
if (!lowerCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one lowercase character !");
flag=false;
}
if (!digitCasePatten.matcher(passwordhere).find()) {
errorList.add("Password must have at least one digit character !");
flag=false;
}
if(flag) System.out.println("the pass is right");
return flag;
}

else if( ... &&passwordhere.length() < 8 ...) <-- sth wrong here.
But I think u don't need else if. After checking all, it's true or false.
So just
if (flag){
System.out.println("the pass is right");
}

Related

Checking for digits

I'm trying to figure out this problem. The directions are set hasDigit to true when a three character passCode from a scanner contains a digit.
Code below
import java.util.Scanner;
public class CheckingPasscodes {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
String passCode;
hasDigit = false;
passCode = scnr.next();
hasDigit = Character.isDigit(passCode);
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}
I've entered in the line
hasDigit = Character.isDigit(passCode);
My logic is that character.isDigit is checking the passCode from the scanner, but I keep getting an error.
I've also tried:
hasDigit = Character.isDigit(0);
and the first test passes, but not the other. From this I assumed that I would have to enter in the string so it would test for anything, not just the character at position 0.
Thanks for the help.
import java.util.Scanner;
public class CheckingPasscodes {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
boolean hasDigit;
String passCode;
hasDigit = false;
passCode = scnr.next();
if ((Character.isDigit(passCode.charAt(0))) || (Character.isDigit(passCode.charAt(1))) || (Character.isDigit(passCode.charAt(2)))) {
hasDigit = true;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
}
}
for(int i = 0 ;i <passCode.length();i++) {
hasDigit = Character.isDigit(passCode.charAt(i));
if (hasDigit) {
System.out.println("Has a digit.");
break;
}
}
if(!hasDigit) {
System.out.println("Has no digit.");
}
Pity that the answer was revealed but if you are going to spoil the learning process at least try giving the right code :/
isDigit() function of Character class excepts either one character or an integer. It does not excepts string , that's why you are getting error. You can modify your code to -
hasDigit = false;
passCode = scnr.next();
for(int i = 0 ;i <passCode.length();i++) {
hasDigit = Character.isDigit(passCode.charAt(i));
if(hasDigit)
break;
}
if (hasDigit) {
System.out.println("Has a digit.");
}
else {
System.out.println("Has no digit.");
}
this will give you required result.

Problems with returning proper code using Character Password Java

The issue I am having is when someone enters a password that includes digits, uppercase, and lowercase the program still says they need all them.
I need the program to list all the requirements for a password if they are not met.
For example:
A123456789aa returns: "You need at least one lowercase. Please Enter Your Password:"
It should return: "Enter termination key"
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
boolean condition = true;
while (condition) {
System.out.print("Please Enter Your Password: ");
String password = input.nextLine();
if (password.equals("endofinput")) {
System.out.print("Your password is valid"); condition = false;
} else {
System.out.print(passCheck(password));
condition = true;
}
}
input.close();
}
public static String passCheck(String password) {
String specialChars = "/*!##$%^&*()\"{}_[]|\\?/<>,." + " ";
if (password.length() < 8) {
return ("You need at least 8 characters. ");
} for (int i = 0; i < password.length(); i++) {
if (specialChars.contains(password.substring(i)))
return ("Your password cannot contain special characters. ");
else if (password.equals("password"))
return ("Your password cannot be password. ");
else if(!Character.isUpperCase(password.charAt(i)))
return ("You need at least one uppercase. ");
else if (!Character.isLowerCase(password.charAt(i)))
return ("You need at least one lowercase. ");
else if (!Character.isDigit(password.charAt(i)))
return ("You need at least one digit. ");
}
return "Enter termination key";
}
your passCheck method iterates over all chars, and returns a result if one char does not fullfill one of your requirements. An alternative would be to assume that the input is not valid, until all requirements are fullfilled:
boolean foundUppercase = false;
boolean foundLowercase = false;
boolean foundDigits = false;
//Dont have to do the check for password as input for every letter in the word.
if (password.equals("password"))
return ("Your password cannot be password. ");
for (int i = 0; i < password.length(); i++) {
if (specialChars.contains(password.substring(i)))
//only in this case we can for sure say that the input is not valid
return ("Your password cannot contain special characters. ");
else if (Character.isUpperCase(password.charAt(i)))
foundUppercase=true;
else if (Character.isLowerCase(password.charAt(i)))
foundLowercase= true;
else if (Character.isDigit(password.charAt(i)))
foundDigits = true;
}
if (!foundUppercase) {
// uppercase letter missing
return ("You need at least one uppercase. ");
} else if (!foundLowercase) {
// lower case letter missing
return ("You need at least one lowercase. ");
} else if (!foundDigits) {
// missing digits
return ("You need at least one digit. ");
}
return "Enter termination key";
You can use this validation function
public static String passCheck(String password) {
//String specialChars = "/*!##$%^&*()\"{}_[]|\\?/<>,." + " ";
String expected_pattern = "^[a-zA-Z0-9]{8,}$";
String lowercase_pattern = "(.*)[a-z]+(.*)";
String uppercase_pattern = "(.*)[A-Z]+(.*)";
String digit_pattern = "(.*)[0-9]+(.*)";
if (password == null || password.length() < 8) return ("You need at least 8 characters. ");
if (password.toLowerCase().equals("password")) return ("Your password cannot be password. ");
if (!password.matches(lowercase_pattern)) return ("You need at least one lowercase. ");
if (!password.matches(uppercase_pattern)) return ("You need at least one uppercase. ");
if (!password.matches(digit_pattern)) return ("You need at least one digit. ");
if (!password.matches(expected_pattern)) return ("Your password cannot contain special characters. ");
return "Enter termination key";
}

do while loop prompting user for some input

I'm new to do while loops.
I've attempted to create a do-while loop that checks if the users input is an integer or the character x. If it is neither it prompts the user to try again.
The loop instead prompts the user twice:
Intended output:
Enter answer:
500
//program is succesful
Actual output:
Enter answer:
500
//prompts user for more input
Code:
do {
System.out.println("Enter answer: ");
input = scan.next();
if(input.trim().equals("x"))
{
terminate = false;
break;
}
while (!scan.hasNextInt()) {
input = scan.next();
System.out.println(input + " is not a interger!!");
}
operationResult = scan.nextInt();
valid = false;
} while (valid);
You could always use a try...catch but I think this will be better -
do{
if(scan.hasNextInt()){
operationResult = scan.nextInt();
break;
}else if(scan.next().trim().equals("x")){
break;
}else{
System.out.println("Enter an Integer!!");
}
}while(true);
It checks whether its an integer first, so there's no need of a try...catch
You can use as given below:
It will not check for integer value, however it will check for numeric value entered, may this will help
public class SomeClass {
public static void main(String args[]) {
try (Scanner scan = new Scanner(System.in)) {
do {
String str = scan.next();
if (isNumeric(str)) {
System.out.println("Program Ends");
break;
} else if (str.equalsIgnoreCase("x")) {
System.out.println("Program Ends");
break;
} else {
System.out.println("Enter Again");
}
} while (true);
}
}
public static boolean isNumeric(String str) {
return !str.matches(".*[^0-9].*");
}
}

Java Doesnt realize if and else

it doesn't realize that there is an if statement when i type a consonant.
and also when i type e, it realizes that its a consonant.
Also when i enter "a" it produces the if statment for string vowel and the else statement.
same with captial letter "A" but this time it produces the else twice.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[])
{
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
if(InputVowel.equals(vowel[x]))
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
else
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is a consaunant");
}
}
}
The reason it can't recognize your if-statements is braces are required if you have more than one if-statement check. If you have an if-else, braces are required.
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
for (int x=0;x<vowels.length;x++) {
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
} else if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
} else {
x = 5;
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");
}
}
The above code should work.
You can only assume it is not a vowel after checking all candidates (all vowels)
String[] vowels = {"a","e","i","o","u"};
String[] vowel = {"A","E","I","O","U"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ");
boolean isVowel = false;
for (int x=0;x<vowels.length;x++)
{
if(InputVowel.equals (vowels[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is a lowercase");
isVowel = true;
break;
}
if(InputVowel.equals(vowel[x])) {
JOptionPane.showMessageDialog(null,InputVowel+" is an uppercase");
isVowel = true;
break;
}
}
if (!isVowel)
JOptionPane.showMessageDialog(null,InputVowel+" is an consaunant");
Although the OP has already accepted an answer. This is an enhanced version of the program utilizing various features of the program.
import javax.swing.JOptionPane;
public class R
{
public static void main(String args[]){
String[] vowels = {"a","e","i","o","u"};
String InputVowel = JOptionPane.showInputDialog(null,"Enter a Character: ").trim();
String x = Integer.toHexString(InputVowel.charAt(0));
for(int i=0;i<vowels.length;i++)
{
if(vowels[i].equalsIgnoreCase(InputVowel))
{
if(!(InputVowel.equals(vowels[i].toUpperCase())))
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a vowel and uppercase character");
break;
}
else if(InputVowel.length()>1||(Integer.valueOf(x)>=0 && Integer.valueOf(x)<=40))
{JOptionPane.showMessageDialog(null,InputVowel+" is not a valid character");break;}
else
{
if(!InputVowel.equals(vowels[i].toUpperCase()))
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and lowercase character");
else
JOptionPane.showMessageDialog(null,InputVowel+" is a consonant and uppercase character");
break;
}
}
}
}
Note
The input other than letters are handled (numbers and special characters) and for simplicity are labelled as non valid characters.

Recursive Palindrome

First of all I am not telling anyone to "do my homework." I just need a little help on how to keep repeating a process. This is the program I did below and it has a tester class with it.
The class:
class RecursivePalindrome {
public static boolean isPal(String s)
{
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
return isPal(s.substring(1, s.length()-1));
return false;
}
}
Then the tester class which has the main method:
public class RecursivePalindromeTester {
public static void main(String[] args)
{
RecursivePalindrome Pal = new RecursivePalindrome ();
boolean quit = true;
Scanner in = new Scanner(System.in);
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
while(quit) {
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
quit = false;
}
else if (x.equals("quit")) {
quit = false;
}
else {
quit = false;
System.out.println(x + " is not a palindrome.");
}
}
}
}
This program find if the letter is Palindrome or not. I got all the calculations and stuff in but what do i do to keep asking the user for input and every time the user inputs it says if it is a Palindrome word or not.
Just move the lines asking for user input and reading it:
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
...into your loop, e.g., just after the
while (quit) {
...line.
Side note: quit seems like an odd name for a boolean which, when true, means you keep going. :-)
Simply wrap with another while loop.
Look into the continue and break statements. They are very helpful for loops, which is what you're looking for information on here.
public class RecursivePalindromeTester {
public static void main(String[] args) {
RecursivePalindrome Pal = new RecursivePalindrome ();
Scanner in = new Scanner(System.in);
while(true){
System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();
boolean itsPal = Pal.isPal(x);
if(itsPal == true){
System.out.println(x + " is a palindrome.");
} else if (x.equals("quit")) {
break;
} else {
System.out.println(x + " is not a palindrome.");
}
}
}
}

Categories

Resources