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");
}
}
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");
So Im taking an intro to Java class through Cengage MindTap and the goal for the assignment was to continuously prompt a user for a password until they enter at least 2 uppercase three lowercase and one number. My code works in JGrasp but when I go to run the checks on mindtap, it seems the program is failing on the second loop after an incorrect password was entered. Below is my code that works on JGrasp and the error I get is:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at ValidatePassword.main(ValidatePassword.java:13)
import java.util.*;
public class ValidatePassword {
public static void main(String[] args) {
boolean valid = false;
while (valid == false)
{
String password;
int lowerCase = 0;
int upperCase = 0;
int numbers = 0;
System.out.println("Enter a password: ");
Scanner keyboard = new Scanner(System.in);
password = keyboard.nextLine();
for(int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
if (Character.isUpperCase(c))
{
upperCase++;
}
if (Character.isLowerCase(c))
{
lowerCase++;
}
if (Character.isDigit(c))
{
numbers++;
}
}
if (upperCase >= 2 && lowerCase >= 3 && numbers >= 1)
{
System.out.println("Valid password");
valid = true;
//valid set to true to break the while loop and end program.
}
else
System.out.println("The password did not have enough of the following:");
if (upperCase < 2)
System.out.println("uppercase letters");
if (lowerCase < 3)
System.out.println("lowercase letters");
if (numbers < 1)
System.out.println("digits");
}
}
}
I'm trying to make a program that sees if a user-entered letter is in the string "hello", and if it is, print that it is in the string and where it is in the string. The error is "bad operand types for binary operator"
String str = "hello", guess;
int testing = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a letter: ");
guess = scan.nextLine(); // Enters a letter
// finds the letter in the string
while (str.charAt(testing) != guess && testing != 6) {
testing++; // Continues loop
}
//prints where letter is if it is in the string
if (str.charAt(testing) == guess)
System.out.println("The letter is at "+testing);
else
System.out.println("Could not find that letter.");
You are trying to compare a char to a String.
Compare a char to a char:
while (str.charAt(testing) != guess.charAt(0) && testing != 6)
and
if (str.charAt(testing) == guess.charAt(0))
I'd also change your stopping condition to avoid StringIndexOutOfBoundsException when no match is found:
while (testing < str.length () && str.charAt(testing) != guess.charAt(0))
and
if (testing < str.length () && str.charAt(testing) == guess.charAt(0))
String str = "hello";
char guess;
int testing = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a letter: ");
guess = scan.next().charAt(0); // Enters a letter
// finds the letter in the string
while (str.charAt(testing) != guess && testing != 5) {
testing++; // Continues loop
}
//prints where letter is if it is in the string
if (str.charAt(testing) == guess)
System.out.println("The letter is at "+(testing+1));
else
System.out.println("Could not find that letter.");
I've tried this and it works. Note that there are two "l" so it will show only the position of the first one
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
The goal of this code is to create a basic hangman game. Everything works fine up until the last step. After the user guesses all the letters it's supposed to display "You guessed it", but the loop seems to execute one extra time. I tried changing the loop code to:
while(guessedLetters < asteriskAmount - 1) but that just made the loop end one time too early.
Any help is much appreciated.
import java.util.Scanner;
public class SecretPhrase {
public static void main(String[] args) {
char userChoice;
String secretPhrase = "GO TEAM";
Scanner input = new Scanner(System.in);
String hint = "G* T***";
StringBuilder secretWord = new StringBuilder(hint);
System.out.println("The hint is " + hint);
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes
int asteriskAmount = hint.length() - 1; // "-1" for the space.
int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed.
while(guessedLetters < asteriskAmount) {
boolean isInPhrase = checkLetter(userChoice, secretPhrase);
if(isInPhrase) { // if the guessed letter is a letter in the phrase...
int position = getPosition(userChoice, secretPhrase);
secretWord.setCharAt(position, userChoice);
hint = secretWord.toString();
guessedLetters++;
System.out.println(secretWord);
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}
else {
System.out.println("That letter is not in the phrase. Please try again >>> ");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}
}
System.out.println("You got it! The secret word is " + secretWord);
}
public static boolean checkLetter(char userChoice, String secretPhrase) {
boolean isInPhrase = false;
int amountOfLetters = 0;
for(int x = 0; x < secretPhrase.length(); x++) {
if(userChoice != secretPhrase.charAt(x)) {
isInPhrase = false;
}
else {
isInPhrase = true;
amountOfLetters++;
}
}
if(amountOfLetters >= 1) {
isInPhrase = true;
}
return isInPhrase;
}
public static int getPosition(char userChoice, String secretPhrase) {
int position;
int x = 0;
while(userChoice != secretPhrase.charAt(x)) {
x++;
}
position = x;
return position;
}
}
This is my output:
The hint is G* T***
Please guess a letter
**o**
GO T***
Please guess a letter
**e**
GO TE**
Please guess a letter
**a**
GO TEA*
Please guess a letter
**m**
GO TEAM
Please guess a letter
**a**
You got it! The secret word is GO TEAM
Remove these lines from before the loop
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
Now inside the loop, move those same lines to the beginning of the loop.
while(guessedLetters < asteriskAmount) {
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
boolean isInPhrase = checkLetter(userChoice, secretPhrase);
if(isInPhrase) { // if the guessed letter is a letter in the phrase...
int position = getPosition(userChoice, secretPhrase);
secretWord.setCharAt(position, userChoice);
hint = secretWord.toString();
guessedLetters++;
System.out.println(secretWord);
}
else {
System.out.println("That letter is not in the phrase. Please try again >>> ");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}
}
Edit: To check for multiple instances of the chosen letter without using arrays, try using this in place of your replacement code
for(int r=0; r<secretPhrase.length(); r++){
if(secretPhrase.charAt(r) == userChoice){
secretWord.setCharAt(r, userChoice);
guessedLetters++;
}
}
With this, you should no longer need the getPosition method or position variable.
full loop with suggested alterations
while(guessedLetters < asteriskAmount) {
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
boolean isInPhrase = checkLetter(userChoice, secretPhrase);
if(isInPhrase) { // if the guessed letter is a letter in the phrase...
for(int r=0; r<secretPhrase.length(); r++){
if(secretPhrase.charAt(r) == userChoice){
secretWord.setCharAt(r, userChoice);
guessedLetters++;
}
}
System.out.println(secretWord);
}
else {
System.out.println("That letter is not in the phrase. Please try again >>> ");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}
}
The problem is that you are always asking again after incrementing guessedLetters. So it's always going to ask one extra time. Try reordering things, for example:
//System.out.println("Please guess a letter");
//userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes
final int asteriskAmount = hint.length() - 1; // "-1" for the space.
int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed.
while (guessedLetters < asteriskAmount) {
System.out.println(secretWord);
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
final boolean isInPhrase = checkLetter(userChoice, secretPhrase);
if (isInPhrase) { // if the guessed letter is a letter in the phrase...
final int position = getPosition(userChoice, secretPhrase);
secretWord.setCharAt(position, userChoice);
hint = secretWord.toString();
guessedLetters++;
} else {
System.out.println("That letter is not in the phrase. Please try again >>> ");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}
System.out.println(guessedLetters);
}
Grab the user input inside your while loop. What was happening was that at the final loop, you go through validating the user input, and then ask for another user input at the end of the loop. The game tries and finish but before it can finish it has to go through that last user input in the while. I always try and put my user input at the beginning of the loop so stuff like this does not happen. Hope this helps!
System.out.println("The hint is " + hint);
//Move the 2 lines below inside your loop
//System.out.println("Please guess a letter");
//userChoice = Character.toUpperCase(input.nextLine().charAt(0)); //Taking the input and turning to uppercase for comparing purposes
int asteriskAmount = hint.length() - 1; // "-1" for the space.
int guessedLetters = 2; // for the 'G' and the 'T' that are already displayed.
while(guessedLetters < asteriskAmount) {
//Moved from above
System.out.println(secretWord);
System.out.println("Please guess a letter");
userChoice = Character.toUpperCase(input.nextLine().charAt(0));
boolean isInPhrase = checkLetter(userChoice, secretPhrase);
if(isInPhrase) { // if the guessed letter is a letter in the phrase...
int position = getPosition(userChoice, secretPhrase);
secretWord.setCharAt(position, userChoice);
hint = secretWord.toString();
guessedLetters++;
//These are not needed any more
//System.out.println(secretWord);
//System.out.println("Please guess a letter");
//userChoice = Character.toUpperCase(input.nextLine().charAt(0));
}