Do-While loop issue, making the prompt run again -JAVA - java

I am attempting to make it so this program runs again if the user enters 'y'. What happens when the user does this is the program runs again, but not correctly. This is what I have so far. I know a do while loop will be best for this. Is it an error in how the variables are initialized?
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
String runAgain = "";
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
do {
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t" + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toLowerCase()); //lowercase version of the password equals the password,
hasLowercase = !password.equals(password.toUpperCase()); //only if it does not contain uppercase letters.
hasDigit = password.matches(".*[0-9].*");//checks for digits
hasSpecial = !password.matches("[A-Za-z0-9]*"); //for anything not a letter in the ABC's
//prints the verdict
System.out.print("Verdict: ");
if(hasLength)
{
System.out.println("\t\tInvalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("\t\t\tInvalid, Must have an uppercase character");
}
if(!hasLowercase)
{
System.out.println("\t\t\tInvalid, Must have a lowercase character");
}
if(!hasDigit)
{
System.out.println("\t\t\tInvalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("\t\t\tInvalid, Must have a special character");
}
System.out.print("Would you like to make another password? (Y/N) ");
runAgain = scan.next();
System.out.println("\n");
} while (runAgain.equalsIgnoreCase("Y"));
which gives this output when yes is entered to run again. It skips the prompt entirely.
Would you like to make another password? (Y/N) y
A password must be at least 8 character long
And must contain:
-At least 1 number
-At least 1 uppercase letter
-At least 1 special character (!##$%^&*()_+)
Please enter your new password:
Entered Password:
Verdict: Invalid, Must have at least 8 characters
Invalid, Must have an uppercase Character
Invalid, Must have a lowercase character
Invalid, Must have a number
Invalid, Must have a special character
Would you like to make another password? (Y/N)

You would need to read the complete line form console at runAgain = scan.next();. Just single token is being read to runAgain and the console is left with \r or Return character which will be read as next password where you do scan.nextLine(). You may change the statement to runAgain = scan.nextLine().trim();.

System.out.print("Would you like to make another password? (Y/N) ");
// runAgain = scan.next();
runAgain = scan.nextLine();
System.out.println("\n");

Related

Need to validate code inputted by user which include letters and numbers

Basically I want the user to enter a code in this format - XXXX000 and if the user enters 3 letters and 4 digits for example - it outputs an error.
What i did is that i wrote a command that input has to be maximum 7 characters but it doesn't specify what the characters need to be. Therefore if user enters 7 digits, it is still accepted which it should not.
System.out.print("Enter the animal's unique code - Format: (XXXX111)");
String codein = in.nextLine();
a.setCode(codein);
if (codein.length() != 7) {
System.out.println("Format was not met, please try again");
System.out.println("Enter the animal's unique code - Format: (XXXX111)");
codein = in.nextLine();
a.setCode(codein);
}
An error should appear if user does not enter in this format XXXX000
Assuming that X means A-Z and a-z and 0 means 0-9 in your pattern, you can use this pattern to valid the code:
[A-Za-z]{4}\d{3}
For more info on regexes, see here.
Use it like this:
if (codeine.matches("[A-Za-z]{4}\\d{3}")) {
// valid
} else {
// invalid
}

How to control how many letters and numbers the user enters into an input prompt?

I'm new to programming and we were given our first assignment! My whole code is working fine, but here is my problem:
We have to prompt the user to enter in an account ID that consists of 2 letters followed by 3 digits.
So far I only have a basic input/output prompt
//variables
String myID;
//inputs
System.out.println("Enter your ID:");
myID = input.nextLine();
So all it does is let the user enter in how many letters and digits they want, in any order and length. I don't understand how to "control" the user's input even more.
As you said you are not aware of regex ,I have written this code to iterate by while loop and check if each character is a alphabet or digit. User is prompted to provide account number till the valid one is entered
import java.util.Scanner;
class LinearArray{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
boolean isIdValid = false;
String myId;
do{
System.out.println("account ID that consists of 2 letters followed by 3 digits");
myId = input.nextLine();
//Check if the length is 5
if (myId.length() == 5) {
//Check first two letters are character and next three are digits
if(Character.isAlphabetic(myId.charAt(0))
&& Character.isAlphabetic(myId.charAt(1))
&& Character.isDigit(myId.charAt(2))
&& Character.isDigit(myId.charAt(3))
&& Character.isDigit(myId.charAt(4))) {
isIdValid = true;
}
}
}while(!isIdValid);
}
}

Boolean help: Testing the parameters for a password JAVA [duplicate]

This question already has answers here:
How to check whether a string contains lowercase letter, uppercase letter, special character and digit?
(6 answers)
Closed 7 years ago.
Task:
This program should check if an entered password is at least 8 characters long, one upper and lowercase letter, a number, and a special character.
Code:
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t " + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toUpperCase());
hasLowercase = !password.equals(password.toLowerCase());
hasDigit = !password.matches("[0-9]");//checks for digits
hasSpecial = !password.matches("[A-Za-z]*"); //for anything not a letter in the ABC's
// the following checks if any of the instances are false, of so prints the statement
if(hasLength)
{
System.out.println("Verdict: Invalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("Verdict: Invalid, Must have an uppercase Character");
}
if(!hasLowercase)
{
System.out.println("Verdict: Invalid, Must have a lowercase Character");
}
if(!hasDigit)
{
System.out.println("Verdict: Invalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("Verdict: Invalid, Must have a special character");
}
If I input the password 'water' and I get:
Entered Password: water
Verdict: Invalid, Must have at least 8 characters
Verdict: Invalid, Must have a lowercase Character
Verdict: Invalid, Must have a special character
I think the upper and lowercase checks should be done vice-versa:
hasUppercase = !password.equals(password.toLowerCase());
hasLowercase = !password.equals(password.toUpperCase());
Because the lowercase version of the password equals the password, only if it does not contains uppercase letters.
The other two check can be done like this:
hasDigit = password.matches(".*[0-9].*");
hasSpecial = !password.matches("[A-Za-z0-9]*");

Searching a string for a non-letter character in a loop

So let's imagine we have this loop that obtains input from the user in the form of strings. With that input, what we want to do is set up a set of validations that will check if certain criteria are met. If all of these conditions are met, it'll complete the action in question. However; if it doesn't, it'll tell them the error and restart the process.
My question is about validating the existance (or non-existance) of a letter in a string. I have this program and for one of these validations, I need to check the entire string. If the string does not have at least one character that isn't a letter, I want to halt the action and explain that a non-letter character is required.
The problem is that I am not sure how I could replicate this in an expression in an if loop. Here's what I have so far.
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}
Assuming by "letter" you mean an english character in A-Z, a-z, just iterate through the string and return true if you encounter a character whose int value is outside the letter range.
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}
I am making the assumption that by letter you meant alphabets. If you use regex pattern you can have a very clean code as well you have ability to update the pattern as necessary. To learn more check Java Pattern. Here is the code.
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}

Regular Expression in Java: Validating user input

I am trying to validate user input using a regular expression in a while loop. I am trying to accept only one lower-case word (letters a-z inclusive).
public class testRedex{
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.print("Please enter a key: ");
while(!console.hasNext("[a-z]+")){
System.out.println("Invalid key");
console.next();
}
String test = console.next();
System.out.println(test);
}
}
My question is, is there any difference between having the regular expression as "[a-z]+" and "[a-z]+$"? I know that $ will look for a character between a-z at the end of the string, but in this case would it matter?
Yes there is a difference, if you'll use: ^[a-z]+$ it means that whatever the user inputs should be combined only from [a-z]+.
If you don't add the ^ and the $ the user could insert other characters, space for example, and there will still be a match (the first part of the string until the space.
Let's see an example:
run your code with the input: "try this" (it'll print "try")
now change the regex to ^[a-z]+$ and run with the same input (it'll print "Invalid key").
The way I would re-write it is:
System.out.print("Please enter a key: ");
String test = console.nextLine();
while (!test.matches("^[a-z]+$")) {
System.out.println("Invalid key");
test = console.nextLine();
}
System.out.println(test);
The difference are as follows
[a-z]+ means a,b,c,...,or z occurs more than one time
[a-z]+$ means a,b,c,...,or z occurs more that one time and must match end of the line
Yet at the end, they give you the same result.
if you want to understand it better try this
([A-Z])([a-z]+$)
It start with a capital letter and end with more than one time small letter
output:
Please enter a key: AAAAaaaa
Invalid key
Aaaaaa
Aaaaaa
Another way you can get the expected result from what you are looking for
code:
int i = 0;
String result = "";
do{
Scanner input = new Scanner(System.in);
System.out.println("Enter your key:");
if(input.hasNext("^[a-z]+$")){
result = input.next();
i=1;
}else{
System.out.println("Invalid key");
}
}while(i==0);
System.out.println("the result is " + result);
output:
Enter your key:
HHHh
Invalid key
Enter your key:
Hellllo
Invalid key
Enter your key:
hello
the result is hello

Categories

Resources