import java.util.Scanner;
public class Exercise6_18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.next();
passWordIsValid(pWT);
}
public static void passWordIsValid (String password) {
boolean passWordIsValid;
if (password.length() < 8) {
passWordIsValid = false;
}
else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}
else
passWordIsValid = true;
if (passWordIsValid == true)
System.out.print("Password is valid");
else if (passWordIsValid == false)
System.out.println("Password is invalid");
}
}
I am trying to write a program that prompts the user to enter a password that is at least 8 characters long, contains at least two digits and is comprised of only letters and digits but when I enter: password12 it says password is invalid. P.S. I know I haven't added the requirement for at least two digits in the method.
...else if (password.indexOf(0) == -1 && password.indexOf(1) == -1
&& password.indexOf(2) == -1 && password.indexOf(3) == -1
&& password.indexOf(4) == -1 && password.indexOf(5) == -1
&& password.indexOf(6) == -1 && password.indexOf(7) == -1
&& password.indexOf(8) == -1 && password.indexOf(9) == -1) {
passWordIsValid = false;
}...
What are you trying to achieve with this code? It doesn't make any sense at all. You probably want to loop over every character of the string instead while counting for every character if it is a digit (and you could "break;" out of the loop as soon as your count is >=2).
Also: Don't save passwords in strings... they will stay in the string pool for quite a while and can be read from memory by malicious programs. You can use a char[] instead.
If you do not want to use Regex, you can use a simple for loop and if statement, you may do something like this:
import java.util.Scanner;
public class PromptPassword {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Password rules:\n"
+ "Password must have at least eight characters\n"
+ "Password must consist of only letters and digits\n"
+ "Password must contain at least two digits\n"
+ "Enter a password:");
String pWT = sc.nextLine(); //read the entire line
passWordIsValid(pWT.trim()); // to remove leading spaces (if any)
}
public static void passWordIsValid (String password) {
boolean passWordIsValid = true;
int noOfDigits =0;
if (password.length() > 8) { // if it's less than 8 chars -> no need to continue
for(char c : password.toCharArray()){
if(Character.isDigit(c)){ // if it's a digit, increment
noOfDigits++;
}
else if(!Character.isAlphabetic(c)){ // if it's not a digit nor alphapet
passWordIsValid = false;
break;
}
}
}
if (passWordIsValid && noOfDigits>=2){
System.out.print("Password is valid");
}
else{
System.out.println("Password is invalid");
}
}
}
Test
Enter a password: abcd12 -> Password is invalid (less than 8)
Enter a password: abcde#123 -> Password is invalid (contains special char)
Enter a password: abcdefghi1 -> Password is invalid (less than 2 digits)
Enter a password: abcdefg12 -> Password is valid (9 in length and contains 2 digits and no special chars)
Your algorithm will not check whether there are at least two digits, and will not check that there are only printable characters and digits in it. Instead of checking for indexOf() you need to loop through all of the characters and count the number that are digits, and ensure each one is either a digit or an alphabetic character, keeping track of the number that are digits.
Use Regex to validate password. positive Lookahead does very good job at validating strings.
Example in java
public static void main(String[] args) {
String passwd = "aaZZa44#";
String pattern = "^(?=.*[0-9].*[0-9])(?=.*[a-z])(?=.*[A-Z]).{8,}$";
System.out.println(passwd.matches(pattern));
}
(?=.*[0-9].*[0-9]) at least 2 digits.
(?=.*[a-z]) lower case a-z
(?=.*[A-Z]) upper case A-Z
{8,} 8 digit in length
Related
I am trying to get the code to check for special characters entered, however, I am not getting any validation errors when special characters are not entered in the password. Is there a reason why special characters are not been identified? All the other password validation checks work fine
//package sampleProject;
import java.util.*;
import java.util.Scanner;
public class Lab7 {
public static void main(String []args){
// Specify the maximum number of letters in a password
final int MAX=10;
int invalidCount = 0;
// Specifying the number of uppercase letters in password
final int MIN_Uppercase=1;
// Specifying the minimum lowercase letters in password
final int NUM_Digits=2;
// Specify the minimum number of special case letters
final int Special=1;
// Count number of uppercase letters in a password
int uppercaseCounter=0;
// Count digits in a password
int digitCounter=0;
// count special case letters in a password
int specialCounter=0;
System.out.println("Enter the password\n");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
for (int i=0; i < password.length(); i++ ) {
char c = password.charAt(i);
if(Character.isUpperCase(c))
uppercaseCounter++;
else if(Character.isDigit(c))
digitCounter++;
if(c == '$' || c == '#' || c == '?' || c == '!' || c == '_' || c == '=' || c == '%'){
specialCounter++;
}
}
if (password.length() >= MAX && uppercaseCounter >= MIN_Uppercase && specialCounter == 1 && digitCounter == 2 || digitCounter == 3) {
System.out.println("Valid Password");
}
else {
System.out.println("Your password does not contain the following:");
if(password.length() < MAX)
System.out.println("Enter atleast 10 characters");
if (uppercaseCounter < MIN_Uppercase)
System.out.println("Enter at least 1 uppercase character");
if(digitCounter != 2 || digitCounter != 3)
System.out.println("Enter either 2 or 3 digits");
if(specialCounter > 1)
System.out.println("Password should contain only 1 special characters");
}
}
}
What you should do this instead in this line :
if(specialCounter != 1)
System.out.println("Password should contain only 1 special characters");
if it is not equal to 0, it will throw the exception. The != means not equal, so if it is less or above 1, It will do the error.
You don't get any validaton errors when special characters are not entered because this is not what your check does:
if(specialCounter > 1)
System.out.println("Password should contain only 1 special characters");
You are printing an error message when there are more than one special characters (which doesn't make sense). I suggest:
if(specialCounter < 1)
System.out.println("Password should contain at least 1 special characters");
I am a student going into software engineering and am taking my first computer science class on coding with java. I'm struggling to get my program to apply a certain set of conditions to a String in order to print a message regarding whether or not a user's input is indeed a valid double literal.
Here are the conditions:
Consists of exactly the following characters: ’+’, ’-’, ’.’ (decimal point), and ’0’ through ’9’
Either the ’+’ or ’-’ character may appear only as the first character
The ’.’ (decimal point) character must appear exactly once
All other characters must be the ’0’ through ’9’ characters
And here is my code:
String doubleliteral;
int a;
char j;
char k;
char l;
char m;
char n;
System.out.print("Enter a valid four character double literal: ");
doubleliteral = keyboard.nextLine();
a = doubleliteral.length();
j = doubleliteral.charAt(0);
k = doubleliteral.charAt(1);
l = doubleliteral.charAt(2);
m = doubleliteral.charAt(3);
n = '.';
char i = (char)(a + 0);
if (i <= 4)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else if ((j == '+') || (j == '-') || (j <= 9))
{
}
else if ((k <= 9))
{
}
else if (l <=9)
{
}
else if (m <= 9)
{
}
else if ((j != '.') && (k != '.') && (l != '.') && (m != '.'))
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
keyboard.close();
I've been searching on the internet, in my textbook, and through my professor's presentations for about three days now trying to figure this out but nothing has come of it, please help.
Here is some psudo-code to get you in the right direction. I can't write your school answer here.
Loop through each character. Special case the first. Track if you have dot.
hasDot = false
for (i=0; i<input.length; i++) {
ch = input[i]
if (i === 0) {
validChars = [0,1,2,3,4,5,6,7,8,9,-,+,.]
// validChars must contain ch
// if ch === dot, set hasDot = true
}
else {
validChars = [0,1,2,3,4,5,6,7,8,9,.]
// validChars must contain ch
// if ch === dot and hasDot then error, else set hasDot = true
}
}
There are few conditions you need to check to figure out the validity. Let's see one by one.
+ Or -
There can be maximum one + or - operator and it has to be at the beginning of the given input.
So what you can do is, whenever you're getting a + or - operator, just check whether current index is 0 or not.
If it's not, then mark the input as invalid.
boolean isValid = true;
for(int i = 0; i < doubleliteral.length(); i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
}
else
{
// it's valid.
}
}
}
The . (decimal point) character
There can be maximum one . character.
So you keep a count of it, check if it ever becomes more than 1.
boolean isValid = true;
int dotCounter = 0;
for(int i = 0; i < doubleliteral.length(); i++)
{
if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
}
else dotCounter++;
}
}
Check if there's any character other than digits (o to 9)
While traversing each character of the string, you can check if it's digit or not like following-
for(int i = 0; i < doubleliteral.length(); i++)
{
if(Character.isDigit(doubleliteral.charAt(i)))
{
// it's a digit
}
}
Now if we combine everything it'll look like this:
boolean isValid = true;
int dotCounter = 0;
int doubleliteralLength = doubleliteral.length();
for(int i = 0; i < doubleliteralLength; i++)
{
if((doubleliteral[i] == '+' || doubleliteral[i] == '-'))
{
if(i != 0)
{
isValid = false;
break; // we don't need to check any further
}
}
else if( doubleliteral[i] == '.')
{
if(dotCounter != 0)
{
isValid = false;
break;
}
else dotCounter++;
}
else if(Character.isDigit(doubleliteral.charAt(i)) != true)
{
// it's not a digit, not + or -, not .
isValid = false;
break;
}
}
if(doubleliteralLength == 4 && isValid)
{
System.out.print("\n" + doubleliteral + " is a valid four character double literal.");
}
else
{
System.out.print("\n" + doubleliteral + " is not a valid four character double literal.");
}
This question can be easily answered by using Regular Expressions and apply the expression to the inputted String object. Although this question is technically correct, it is not correct for the lesson your professor is teaching (which I am guessing is String parsing).
That said, here are my clues to you:
Symbols (+ or -) can only be present at character index 0.
The (decimal) ASCII values for numbers 0-9 are 48-57. Therefore, an ASCII
value outside this range that is not a "+", "-", or "." (43, 45, or
46 respectively) is an illegal character.
The next thing you need to do is write down a few combinations of characters and test them out manually. For example:
1.34 // invalid (first character must be the sign)
.123 // invalid (first character must be the sign)
-.98 // valid
-0.1 // valid
+2.3 // valid
2.+6 // invalid
4.3- // invalid
30-4 // invalid
+23. // valid (by your requirements, but it should not be)
+0.- // invalid
All of the above contain nothing but valid characters, but not all are correctly formatted. Once you test these out, you should try using other non-numeric characters.
Your code should be something like this (in psedocode)
IF STRING LENGTH > 4, ERROR (String has too many characters)
IF PERIOD COUNT > 1, ERROR // See * note
IF CHAR AT 0 NOT VALID, ERROR (Special case for symbols, period, or numbers)
IF CHAR AT X NOT VALID, ERROR (index 1-3 can only be numbers or the period)
IF CHAR AT 3 == ., ERROR (Last index cannot be the period)
PRINT STING MESSAGE
(*) My suggestion is to use a loop operation to count the number of times the period appears on the String. There are other ways to do this, but my guess is that they are not related to your current lesson. Some of those alternative methods are using regular expressions, using Streams API, using recursion, or using 3rd party libraries. Stay away from any of those solutions.
If all the tests passed, then the only thing that will be printed out will be the message containing the valid numeric string.
Last hint: Do all of the CHAR AT evaluations in a single pass (i.e. loop through your String (array of characters) to determine if the character at any given position is valid. A multiple pass solution is OK, just not elegant or effective.
The solution
import java.util.Scanner;
public class NumericStringEvaluator {
public static void main (String[] args) {
System.out.print("Enter a valid four character double literal: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
scanner.close();
if (input.length() > 4) {
System.err.println("String must be exactly 4 characters");
System.exit(-1);
}
//1. Consists of exactly the following characters: ’+’, ’-’ ...
//2. Either the ’+’ or ’-’ character may appear only as the first character
if (input.charAt(0) != '+' && input.charAt(0) != '-') {
System.err.println("Invalid character at index 0: " + input.charAt(0));
System.exit(0);
}
int periodCount = 0;
for (int i = 1; i < 4; i++) {
char c = input.charAt(i);
//1. Consists of ... ’.’ ...
if (c == '.') {
periodCount++; //3. The ’.’ (decimal point) character must appear exactly once
}
// 1. Consists of ... and ’0’ through ’9’
// 4. All other characters must be the ’0’ through ’9’ characters
// ASCII values for number are 48-57 (anything outside the range is not a number)
// and the special characters have been accounted for already
else if (c < 48 || c > 57) {
System.err.println("Invalid character at index " + i + ": " + input.charAt(i));
System.exit(0);
}
}
// At this point, every character in the string has been validated (no errors found)
//3. The ’.’ (decimal point) character must appear exactly once
if (periodCount != 1) {
System.err.println("Decimal point appears more than once in numeric String.");
System.exit(0);
} else {
System.out.print("\n" + input + " is a valid four character double literal.");
}
}
}
I'm trying to create a Java program that checks to see if an input password has at least three lowercase letters, 2 uppercase letters, and 1 digit. This is what I have so far:
Scanner inputDevice = new Scanner(System.in);
boolean valid= false;
String password;
do{
System.out.print("Enter a password that contains at least 2 uppercase letters, three lowercase letters, and at least 1 digit: ");
password = inputDevice.nextLine();
boolean Upper;
boolean Lower;
boolean Digit;
int UpperCount=0;
int LowerCount=0;
int DigitCount=0;
for(int i=0; i<password.length(); i++){
if (Character.isUpperCase(password.charAt(i)));
UpperCount++;}
if (UpperCount<2)
Upper=false;
else
Upper=true;
for(int i=0; i<password.length(); i++){
if (Character.isLowerCase(password.charAt(i)));
LowerCount++;}
if (LowerCount<3)
Lower=false;
else
Lower=true;
for(int i=0; i<password.length(); i++){
if (Character.isDigit(password.charAt(i)));
DigitCount++;}
if (DigitCount<1)
Digit=false;
else
Digit=true;
if ((Digit == false) || (Upper == false) || (Lower == false))
System.out.print("The password did not have enough of the following:");
if (Upper == false)
System.out.print("\nuppercase letters");
if (Lower == false)
System.out.print("\nlowercase letters");
if (Digit ==false)
System.out.print("\ndigits");
if ((Digit==true)&&(Upper==true)&&(Lower==true))
valid=true;
}while(valid!=true);
System.out.println("Valid password");
I have been wrestling with it for a while now. Some problems I have had have been:
The counts not resetting to zero when returning to the top of the loop.
The loop not recognizing digits or putting completely wrong outputs based on my test runs.
Now it is just skipping the loop entirely and goes to the Valid Password statement no matter what I type into the input to test.
At this point I am really frustrated and could use some help.
Get rid of your semicolons. if (Character.isUpperCase(password.charAt(i))); should just be if (Character.isUpperCase(password.charAt(i))) and same for the other 2 if statements. Also, just as a sidenote for readability, I recommend moving your brackets to new lines so it's easier to see where your for loop ends. Originally I thought you had 3 if statements for each for loop but then I saw the bracket hidding in your first if statement
Use below
import java.util.Scanner;
public class Main{
public static void main(String []args){
Scanner inputDevice = new Scanner(System.in);
boolean valid= false;
String password="";
do{
System.out.print("\nEnter a password that contains at least 2 uppercase letters, three lowercase letters, and at least 1 digit: ");
password = inputDevice.nextLine();
boolean Upper=false;
boolean Lower=false;
boolean Digit=false;
int UpperCount=0;
int LowerCount=0;
int DigitCount=0;
for(int i=0; i<password.length(); i++){
if (Character.isUpperCase(password.charAt(i)))
UpperCount++;
else if(Character.isLowerCase(password.charAt(i)))
LowerCount++;
else if(Character.isDigit(password.charAt(i)))
DigitCount++;
}
if (UpperCount>=2)
Upper=true;
if (LowerCount>=3)
Lower=true;
if (DigitCount>=1)
Digit=true;
if ((Digit == false) || (Upper == false) || (Lower == false))
System.out.print("The password did not have enough of the following:");
if (Upper == false)
System.out.print("\nuppercase letters");
if (Lower == false)
System.out.print("\nlowercase letters");
if (Digit ==false)
System.out.print("\ndigits");
if ((Digit==true)&&(Upper==true)&&(Lower==true))
valid=true;
}while(valid!=true);
System.out.println("Valid password");
}
}
I am trying to finish a homework assignment and keep getting two errors and cannot figure out how to fix them. Here is the code:
import java.util.Scanner;
public class GoughAndreaProg5
{
public static void main (String[] args)
{
Scanner stdIn = new Scanner(System.in);
System.out.println("Enter a password that meets the following rules: ");
System.out.println("");
System.out.println("Is atleast 8 characters long");
System.out.println("Contains atleast 1 lower letter character");
System.out.println("Contains atleast 1 upper letter character");
System.out.println("Contains atleast 1 numeric digit");
System.out.println("Contains atleast 1 special character from the set: !##$%^&*");
System.out.println("Does not contain the word \"and\" or the word \"end\"");
System.out.println("");
String myInput = stdIn.nextLine();
boolean digit = false;
boolean upperCase = false;
boolean lowerCase = false;
for(int x=0; x<myInput.length(); x++)
{
if (Character.isDigit(myInput.charAt(x)))
digit = true;
if(Character.isUpperCase(myInput.charAt(x)))
upperCase = true;
if(Character.isLowerCase(myInput.charA(x)))
lowerCase = true;
}
boolean validLength = true;
if (myInput.length() < 8)
{
System.out.println("Must be at least 8 characters long");
validLength = false;
}
boolean special = false;
if(myInput.indexOf('!') != -1 | myInput.indexOf('#') != -1 || myInput.indexOf('#') != -1 || myInput.indexOf('$') != -1 || myInput.indexOf('%') != -1 || myInput.indexOf('^') != -1 || myInput.indexOf('&') != -1 || myInput.indexOf('*') != -1)
special = true;
else //no special character
{
System.out.println("Must contain a special character");
}
boolean word = false;
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
{
word = true;
System.out.println("Contains the string \"and\" or the word \"end\"");
}
if(!digit)
System.out.println("Must have a numeric digit");
if(!upperCase)
System.out.println("Must have an upper case");
if(!lowerCase)
System.out.println("Must hava a lower case");
//output valid or not
if (validLength && special && !word && upperCase && lowerCase && digit)
System.out.println("valid");
else
System.out.println("not valid");
} //end main method
public static void System.out.println(String inStr)
{
System.out.println(inStr);
} //end of alt string print method
} //end of class
The errors are:
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: '(' expected
public static void System.out.println(String inStr)
^
C:\Users\gougha\Documents\Park\Java Class\myJavaPgms\GoughAndreaProg5.java:76: error: <identifier> expected
public static void System.out.println(String inStr)
^
I have tried every thing I can think of. I'm sure it's an easy fix, but this is all so new to me and I can't see it. Thank you!
There are several compile errors with your code
To start
public static void System.out.println(String inStr)
should be (though you don't use it so I suggest just remove this method)
public static void println(String inStr)
Then
if (myInput.indexOf("and") != -1 || myInput.indexOf("end"));
should be
if (myInput.indexOf("and") != -1 || myInput.indexOf("end") != -1);
Finally
if(Character.isLowerCase(myInput.charA(x)))
should be
if(Character.isLowerCase(myInput.charAt(x)))
You do not need to create this method public static void System.out.println(inStr). Infact the syntax is also wrong. You just need to provide a method name when you create it. Not the class name along with it.
// Not required at all
public static void System.out.println(String inStr)
{
System.out.println(inStr);
}
System.out.println() is the inbuilt method to print values to the console. So just use System.out.println(inStr) in your main method, whenever you need to print something on the System's output console.
I'm having difficulty ensuring that doubles are validated correctly in my program. A user can enter an amount to deposit into the account, which should be a double (I know, it's not what I should be using, but it's part of the assignment guidelines). Theoretically, the user should be able to deposit any amount- not just £30, but say, £15.23.
This is the validation I currently have, which allows numbers, but prevents the entry of a full stop, which creates a number of problems.
Here is the code I have so far:
public static String getBalanceValidation()
{
//Allow user input capabilities
Scanner input = new Scanner (System.in);
//Declare variables needed for validation
double dblInput = 0; //dblInput is set as 0
String strNumber = ""; //strNumber is blank
boolean bolSuccessful, bolNumeric;
int intCount;
char charLetter;
do
{
//set bolSuccessful and bolNumeric as true
bolSuccessful = true;
bolNumeric = true;
try //try user input
{
System.out.println("Enter the balance to be deposited: "); //User prompt
strNumber = input.next(); //User input as string
dblInput = Double.parseDouble(strNumber) ; //String input converted to double
}// end of try
catch (NumberFormatException e) //NumberFormatException disallows letters or symbols in value
{
System.out.println("Deposit value cannot contain letters!"); //Error message
bolSuccessful = false; //set bolSuccessful as false
continue; //Return to try
}//end of number format catch
//create for loop which checks each character throughout the string
for (intCount = 0; intCount < strNumber.length(); intCount++)
{
charLetter = strNumber.charAt(intCount); //charLetter is the alphanumeric value of a character in the string at the point dictated by intCount
if (!(charLetter >= '0') && (charLetter <= '9' ) //if charLetter is not between 0 and 9
|| (charLetter == '.')) //or charLetter is not a full stop
{
bolNumeric = false; //Set bolNumeric as false
}//end of if construct
}//end of for loop
if (!bolNumeric) //if bolNumeric is false
{
System.out.println("Incorrect input format! The balance must be numbers only!"); //Error message
bolSuccessful = false; //Set bolSuccessful as false
}//end of if construct
}while (!bolSuccessful); //While bolSuccessful is false, return to top
return strNumber; //return strNumber to be used in main method
//end of do method
}//end of getBalanceValidation method
I'm not sure whether it's because I've used NumberFormatException (is there something else for double?)
Many thanks
You have 2 errors in your boolean expression :
if (!(charLetter >= '0') && (charLetter <= '9' ) || (charLetter == '.'))
This condition is equivalent to :
if ((charLetter < '0') && (charLetter <= '9' ) || (charLetter == '.'))
Which can be simplified to :
if ((charLetter < '0') || (charLetter == '.'))
So the ! should be applied to the first two parts of the expression :
if (!( (charLetter >= '0') && (charLetter <= '9') ) || (charLetter == '.'))
Moreover, since . is not a number, this expression is equivalent to :
if (!( (charLetter >= '0') && (charLetter <= '9') ))
You probably meant && not || :
if (!( (charLetter >= '0') && (charLetter <= '9' ) ) && (charLetter != '.'))
Which means if(not_a_number AND not_a_full-stop)
You can double number = input.nextDouble(); instead of strNumber = input.next();. This would allow you to input the number directly as double instead of String.
You would have to handle InputMismatchException in your catch block, and you are good to go. You won't need to validate to check the inclusion of ..
It would be much easier using a regex:
bolNumeric = strNumber.matches("[1-9][0-9]*(\\.[0-9]{1,2})?");
Explanation: The first number has to be within 1-9. Then as many as you want (including none) other numbers may follow. This is optionally followed by a dot, and then at least one, max 2 more digits.