Im a rookie Java coder, and I am trying to make a very basic username/password program. The username part of it is working fine, but when I get to the password it gives me some weird problems. I figured out that for example when it checks for an Uppercase letter, if it finds one its all good, but if it doesn't, it prints the error message for every single character in the password. It does this with the number check and the length check as well. If any of you guys could explain this to me rather simply since I am still new to java, that would be awesome. Thanks!
do
{
if (count3 >0)
{
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err.println("- At least 7 characters long.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
for(int count = 0; count < regPasswordLen; count++)
{
if(Character.isUpperCase(regPassword.charAt(count)))
regPasswordUppercaseCheck = true;
else
{
System.err.println("Your password did not contain an Uppercase letter");
regPasswordUppercaseCheck = false;
}
if(regPassword.contains("1") || regPassword.contains("2") ||
regPassword.contains("3") || regPassword.contains("4") ||
regPassword.contains("5") || regPassword.contains("6") ||
regPassword.contains("7") || regPassword.contains("8") ||
regPassword.contains("9") || regPassword.contains("0"))
regPasswordNumCheck = true;
else
{
System.err.println("Your password did not contain at least 1 number.");
regPasswordNumCheck = false;
}
if (regPasswordLen >=7)
regPasswordLengthCheck = true;
else
{
System.err.println("Your password did not meet the minimum length requirements.");
regPasswordLengthCheck = false;
}
}
count3++;
}
while(!regPasswordUppercaseCheck || !regPasswordNumCheck || !regPasswordLengthCheck);
System.out.println("test");
You used same variable every time for "if and else" for every different char i.e. regPasswordUppercaseCheck, if every char of your input is in uppercase except the last char, the variable will contain false.
I think you use count3 for making sure that inner code will run single time but if while goes false and count3 condition is remain true then code will stuck in a infinite loop.
Use
while(regPasswordUppercaseCheck && regPasswordNumCheck && regPasswordLengthCheck); for simplicity.
A few things you can change in your program.
do
{
if (count3 >0)
{
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err.println("- At least 7 characters long, but no more than 15 characters.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
// this check only needs to happen once per password, no need to check it in the for loop. You also specified that the length should not exceed 15 characters, so I threw that in as well
if (regPasswordLen < 7 || regPasswordLen > 15)
System.err.println("Your password did not meet the length requirements.");
// by default, we set these flags to false, and only make them true if the requirements are satisfied
regPasswordUppercaseCheck = false;
regPasswordNumCheck = false;
for(int count = 0; count < regPasswordLen; count++)
{
// store the value of regPassword.charAt(count) in a local variable for reusability
char current = regPassword.charAt(count);
if(Character.isUpperCase(current))
regPasswordUppercaseCheck = true;
// checks if the character is a digit or not
if(current >= '0' && current <= '9')
regPasswordNumCheck = true;
}
if (!regPasswordNumCheck)
System.err.println("Your password did not contain at least 1 number.");
if (!regPasswordUppercaseCheck)
System.err.println("Your password did not contain an Uppercase letter");
count3++;
}
while(!regPasswordUppercaseCheck || !regPasswordNumCheck || !regPasswordLengthCheck);
your checking for uppercase is not done right because the loop
for(int count=0;count<regPasswordLength;count++) should not contain the checking if the password contains a number nor the checking if the password is longer than 7 characters so the loop should look like this
for (int count = 0; count < regPasswordLen; count++) {
if (Character.isUpperCase(regPassword.charAt(count)))
{regPasswordUppercaseCheck = true;break;}
}
i use break here to get out of the loop the moment i found that password contains an uppercase after some modifications your code can look like this
do {
if (count3 > 0) {
System.err.println("- At least 1 Uppercase");
System.err.println("- At least 1 number");
System.err
.println("- At least 7 characters long, but no more than 15 characters.");
}
regPassword = input.nextLine();
regPasswordLen = regPassword.length();
for (int count = 0; count < regPasswordLen; count++) {
if (Character.isUpperCase(regPassword.charAt(count)))
{regPasswordUppercaseCheck = true;break;}
}
if(regPasswordUppercaseCheck==false){
System.err
.println("Your password did not contain an Uppercase letter");
regPasswordUppercaseCheck = false;
}
regPasswordNumCheck = regPassword.contains("1") || regPassword.contains("2")
|| regPassword.contains("3")
|| regPassword.contains("4")
|| regPassword.contains("5")
|| regPassword.contains("6")
|| regPassword.contains("7")
|| regPassword.contains("8")
|| regPassword.contains("9")
|| regPassword.contains("0");
if(regPasswordNumCheck==false) {
System.err
.println("Your password did not contain at least 1 number.");
regPasswordNumCheck = false;
}
if (regPasswordLen >= 7)
regPasswordLengthCheck = true;
else {
System.err
.println("Your password did not meet the minimum length requirements.");
regPasswordLengthCheck = false;
}
count3++;
} while (!regPasswordUppercaseCheck || !regPasswordNumCheck
|| !regPasswordLengthCheck);
System.out.println("test");
Related
I am trying to get the password to return and re-ask for the password if an invalid password is entered. And if a password is invalid 3 consecutive times, the system should terminate.
Is there an issue how I have structured the sequence of the lines of code? Please advise as I am rather new to Java.
public static void main(String []args){
final int MAX=10;
int invalidCount = 0;
final int MIN_Uppercase=1;
int uppercaseCounter=0;
int digitCounter=0;
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.isDigit(c))
digitCounter++;
if(Character.isUpperCase(c))
uppercaseCounter++;
if(c == '!' || c == '#' || c == '#' || c == '$' || c == '%' || c == '^' || c == '&' || c == '*' || c == '(' || c == ')' || c == '-' || c == '_' || c == '=' || c == '+'){
specialCounter++;
}
}
if (password.length() >= MAX && uppercaseCounter >= 1 && specialCounter == 1 && (digitCounter == 2 || digitCounter == 3)) {
System.out.println("Valid Password");
}
else {
invalidCount++;
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 only");
if(specialCounter != 1)
System.out.println("Password must contain 1 special character");
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
return;
}
You need to put this entire logic in a while loop that keeps tracks of invalidCount.
The other solution is to put the entire logic in a while loop which is always true and it breaks out of the loop in case correct password is entered.
Also, by seeing the if condition in your code, I would like to point out only the first println statement is inside the if part and not the second println statement.
if (invalidCount == 3)
System.out.println("Maximum tries reached");
System.exit(invalidCount);
but i think you wanted to put it something like this. such that when the count reaches 3, then it should terminate.
if (invalidCount == 3) {
System.out.println("Maximum tries reached");
System.exit(invalidCount);
}
Place the Password prompt into a while loop with a counter, for example:
Scanner userInput = new Scanner(System.in);
int maxPasswordAttempts = 3;
int passwordCounter = 0;
String password = "";
while (password.isEmpty()) {
passwordCounter++;
if (passwordCounter > maxPasswordAttempts) {
System.out.println("Maximum allowable password attempts (" + maxPasswordAttempts
+ ")has been\ncarried out! No longer accepting a passwords!");
System.exit(0);
}
System.out.print("Please enter a password (c to cancel): --> ");
password = userInput.nextLine().trim();
if (password.equalsIgnoreCase("c")) {
System.out.println("Password Entry - CANCELED!");
return;
}
/* Regex from the website:
https://mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/
Give it a read... */
if (!password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!##&()–[{}]:;',?/%*~$^+=<>]).{8,20}$")) {
System.out.println();
System.out.println("INVALID PASSWORD! - Secure Password requirements:\n" +
"-------------------------------------------------\n" +
"Password must contain at least one digit [0-9].\n" +
"Password must contain at least one lowercase Latin character [a-z].\n" +
"Password must contain at least one uppercase Latin character [A-Z].\n" +
"Password must contain at least one special character like: ! # # & ( ). %, etc.\n" +
"Password must contain a length of at least 8 characters and a maximum of 20 characters.\n" +
"Try Again...\n");
password = "";
}
}
System.out.println("\nYour VALID password is: " + password);
System.out.println("Now HASH it! :)");
I'm writing a password validation program and having some issues with the or statement that checks for special characters. I'm not sure what is wrong with it, the rest of the program seems to function properly, but entering a password that matches the criteria, for example, P#ndas123$%, just results in an infinite loop.
I believe that the problem is related to my big statement for the !pass.contains("") portion. If that is right, could someone help me understand why the statement is incorrect?
import java.util.Scanner;
public class DylanJacksonProg5 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
boolean valid;
valid = true;
do {
//Password rules declared to user
System.out.println("Password Verifier");
System.out.println("");
System.out.println("Enter a password that meets the following rules: ");
System.out.println(" Is at least 8 characters long");
System.out.println(" Contains at least 1 lower letter character");
System.out.println(" Contains at least 1 upper letter character");
System.out.println(" Contains at least 1 numeric digit");
System.out.println(" Contains at least 1 special character of the following set: !##$%^&*");
System.out.println(" Does not contain the word 'and' or the word 'the'");
//Gathering password from user
System.out.println("Enter your password: ");
String pass;
pass = user_input.next();
//Validating password to rules
if (pass.length() < 8) {
int shortlen;
shortlen = 8 - pass.length();
System.out.println("Password is too short. Please add " + shortlen + " characters");
valid = false;
} else
System.out.println("Password length is acceptable.");
//Check for character cases
boolean hasUppercase = !pass.equals(pass.toLowerCase());
boolean hasLowercase = !pass.equals(pass.toUpperCase());
if (!hasUppercase) {
System.out.println("Must have an uppercase Character");
valid = false;
}
if (!hasLowercase) {
System.out.println("Must have a lowercase Character");
valid = false;
}
if (hasUppercase) {
System.out.println("Has an upper case character");
}
if (hasLowercase) {
System.out.println("Has a lowercase Character");
}
//Check for digit
for (int i = 0; i < pass.length(); i++) {
char x = pass.charAt(i);
if (!Character.isDigit(x)) {
valid = false;
}
}
//check for special character
if (!pass.contains("!") || !pass.contains("#") || !pass.contains("#") || !pass.contains("$") ||
!pass.contains("%") || !pass.contains("^") || !pass.contains("&") || !pass.contains("*"))
{
valid = false;
System.out.println("Password requires a special character from the following: !##$%^&*");
}
// check for 'and'
if (pass.contains("and")) {
valid = false;
System.out.println("Cannot contain 'and'");
}
//check for 'the'
if (pass.contains("the")) {
valid = false;
System.out.println("Cannot contain 'the'");
}
System.out.println("");
}
while (!valid);
}
}
I'll tell you one problem straight up front.
Since you set valid to true before the validation loop, and only ever set it to false within the loop, entering an invalid password as your first attempt will result in the loop never exiting.
The setting of valid to true should be the first thing done within the loop.
On top of that, your checks each individually apply to every character in the input string, a situation which is impossible. For example, you check whether the entire string is equal to its lowercased variant, then you check whether it's also equal to its uppercased variant.
That means any string with a letter in it will be deemed invalid since xyZZy cannot be equal to both xyzzy and XYZZY at the same time.
It would be more correct to do something like (pseudo-code, and cut down to a few conditions just to show the method):
do:
hasLowercase = false
hasUpperCase = false
hasNumeric = false
isLongEnough = false
get string from user
if len(string) >= 8:
isLongEnough = true
for each character in string:
if character is lowercase:
hasLowerCase = true
if character is uppercase:
hasUpperCase = true
if character is numeric:
hasNumeric = true
isValid = hasLowerCase && hasUpperCase && hasNumeric && isLongEnough
until isValid
This checks each individual character so that any of them (rather than requiring that all of them) will mark a condition as true.
The OR operators will conflict if you don't have all of the special characters in the password, because in your condition statements, if you have "!" but not "#", it will still result in a false value.
What you can do is check for each special character separately.
Sorry for the lack of explanation, but it is your negation statements in your special character checking block. Usually using !condition works, but it didn't on this online IDE I am using. Not really sure why.
This code will work:
//check for special character
if (pass.contains("!") || pass.contains("#") || pass.contains("#") || pass.contains("$") ||
pass.contains("%") || pass.contains("^") || pass.contains("&") || pass.contains("*"))
{
valid = true;
System.out.println("Password requires a special character from the following: !##$%^&*");
}
else
{
valid = false;
}
There are multiple problems with your code, which are unrelated to each other:
You never set valid to true in the loop, which means that if you enter 1 wrong password, valid will be and always stay false, which means that no matter how many correct passwords you enter afterwards, the loop will repeat infinitely. In other words: the program will only stop if you enter a correct password at the very first attempt.
The big boolean expression is not checking whether the password contains any of the characters, it is checking whether the password contains all characters. Draw the truth table or apply DeMorgan's Laws, and you will see:
!p.c("!") || !p.c("#") || !p.c("#") || !p.c("$") || !p.c("%") || !p.c("^") || !p.c("&") || !p.c("*")
// is the same per DeMorgan's Laws as
!(p.c("!") && p.c("#") && p.c("#") && p.c("$") && p.c("%") && p.c("^") && p.c("&") && p.c("*"))
As soon as you find a single character that is not a digit, you reject the password, IOW all characters must be digits.
It should be obvious that #2 and #3 contradict each other, so it it simply impossible to enter a valid password, so even if you fix #1, it will still not be possible to exit the loop.
There are a 3 issues with your code:
valid must be set to true inside your loop before any checks are done on input:
do {
valid = true;
...
lower & upper case checks should be done differently, for example:
boolean hasUppercase = false;
boolean hasLowercase = false;
for (int i = 0; i < pass.length(); i++){
if (Character.isUpperCase(pass.charAt(i))){
hasUppercase = true;
}
if (Character.isLowerCase(pass.charAt(i))){
hasLowercase = true;
}
}
your checks for special character are incorrect, you could use below instead:
if (!(pass.contains("!") || pass.contains("#") || pass.contains("#") || pass.contains("$") || pass.contains("%") || pass.contains("^") || pass.contains("&") || pass.contains("*"))){
valid = false;
}
EDIT: actually there's another one:
4. Your check for digit also won't work, you could use below instead:
boolean isDigit = false;
for (int i = 0; i < pass.length(); i++) {
char x = pass.charAt(i);
if (Character.isDigit(x)) {
//valid = false;
isDigit = true;
break;
}
}
if (!isDigit)
valid = false;
Here's how OR operator works:
if( condition1 || condition2 || condition3 || condition4)
{
// .....your code;
}
If condition1 is true,then remaining conditions will not be checked and program will move to inside your IF block.However,if Condition1 is false,then condition2 will be checked.If this is true,then remaining conditions will not be checked,otherwise(if it is false) condition3 will be checked.and so on.However as other peoples have already mentioned there is more problem with your code than just with OR operator.
For example,for password=P#ndas123$%,it does not contain "!",so !pass.contain("!") will give true and valid will be set as false thus causing infinite loop.
Im trying to turn a string taken from the user into Pig Latin. I cannot use any special classes, methods, or arrays. I can only use a Scanner to create a object to take the string from the user and .length and .charAt, in addition to any type of looping. (Also cannot use switch statements or the break keyword)
Here is an example of what my output is suppose to be:
Enter a line of text: this is a test.
Input : this is a line of text.
Output: his-tay is-way a-way ine-lay of-way ext-tay.
Here is my code, I can only get my code to work with one word and it must have a space at the end. Only one loop works at a time depending on the loop. Im not sure what to do if I get an entire String.
I know that when the user enters a space that signals a new word, and when they enter a period, that signals the ending.
I had a hard time understanding your code. (It looks like you are trying to do it two ways at once?) Regardless, I believe I was able to understand your question. Here is a compilable and runnable example:
import java.util.Scanner;
public class PigLatin
{
public static void main(String[] args)
{
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
if (text != null && text.length() > 0)
{
int i = 0;
// this iterates through the whole string, stopping at a period or
// the end of the string, whichever is closer
while (i < text.length() && text.charAt(i) != '.')
{
// these three variables only exist in this code block,
// so they will be re-initialized to these values
// each time this while loop is executed
char first = '\0'; // don't worry about this, I just use this value as a default initializer
boolean isFirst = true;
boolean firstIsVowel = false;
// each iteration of this while loop should be a word, since it
// stops iterating when a space is encountered
while (i < text.length()
&& text.charAt(i) != ' '
&& text.charAt(i) != '.')
{
// this is the first letter in this word
if (isFirst)
{
first = text.charAt(i);
// deal with words starting in vowels
if (first == 'a' || first == 'A' || first == 'e' || first == 'E'
|| first == 'i' || first == 'I' || first == 'o' || first == 'O'
|| first == 'u' || first == 'U')
{
System.out.print(first);
firstIsVowel = true;
}
// make sure we don't read another character as the first
// character in this word
isFirst = false;
}
else
{
System.out.print(text.charAt(i));
}
i++;
}
if (firstIsVowel)
{
System.out.print("-tay ");
}
else if (first != '\0')
{
System.out.print("-" + first + "ay ");
}
i++;
}
System.out.print('\n'); //for clean otuput
}
}
}
There are a few comments in there that might help guide you through my logic. This is almost definitely not the most efficient way to do this (even with your limitations), as I only whipped it up as a example of the type of logic you could use.
You could break it up into words, then process the current word when you hit a space or period:
System.out.print("Enter a line of text: ");
Scanner keyboard = new Scanner(System.in);
String text = keyboard.nextLine();
System.out.println("\nInput: " + text);
System.out.print("Output: ");
String curWord = "";
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ' ' || text.charAt(i) == '.') {
if (curWord.charAt(0) == 'a' || curWord.charAt(0) == 'e' ||
curWord.charAt(0) == 'i' || curWord.charAt(0) == 'o' ||
curWord.charAt(0) == 'u') {
System.out.print(curWord + "-way ");
} else {
for (int j = 1; j < curWord.length(); j++) {
System.out.print(curWord.charAt(j);
}
System.out.print("-" + curWord.charAt(0) + "ay ");
//System.out.print(curWord.substring(1)+"-"+curWord.charAt(0)+"ay ");
}
curWord = "";
} else {
curWord += text.charAt(i);
}
}
I am trying to complete my programming assignment, I have to create a "Password verifier" that has 1 uppercase, 1 lowercase, 1 number, and 1 special character. If invalid, it must show "invalid" plus the rule that it has shown as false. The problem I have, is not an error message, but I always get a positive response, plus all the violated rules, plus it reads them twice. Little help here?
import java.util.Scanner;
public class PasswordVerifier {
public static void main(String[] args) {
System.out.println("Password Verifier");
System.out.println("Enter a password that meets the following rules: ");
System.out.println("-Must be at least 8 characters long" + '\n' +
"-Must contain at least 1 lower case character" + '\n' +
"-Must contain at least 1 upper case character" + '\n' +
"-Must contain at least 1 numeric digit" + '\n' +
"-Must contain at least 1 special character from the set: !##$%^&*" + '\n' +
"-Must not contain the word 'and' or the word 'end'");
String password;
String contains1 = "and";
String contains2 = "end";
String special = "!##$%^&*";
Scanner stdIn = new Scanner(System.in);
boolean digit = false; //Has at least 1 digit
boolean upper = true; //Has at least 1 upper case letter
boolean lower = true; //Has at least 1 lower case letter
boolean hasspecial = true; //Has at least 1 special character
boolean length = true; //Has at least 8 digits
boolean endand = true; //Does not contain end or and
boolean valid = false; //Is the password valid?
System.out.println("Enter password: ");
password = stdIn.nextLine();
int result;
result = password.indexOf(contains1);
if (result == -1) {
System.out.println("");
} else {
System.out.println("Must not contain the word 'and'");
}
int result2;
result2 = password.indexOf(contains2);
if (result2 == -1) {
System.out.println("");
} else {
System.out.println("Must not contain the word 'end'");
}
if (password.length() < 8) {
System.out.println("Must be at least 8 characters long.");
} else {
System.out.print("");
}
for (int i = 0; i < password.length(); i++) {
if (!(Character.isUpperCase(password.charAt(i)))) ;
{
upper = false;
valid = false;
i++;
}
if (!(Character.isLowerCase(password.charAt(i)))) ;
{
lower = false;
valid = false;
i++;
}
if (!(Character.isDigit(password.charAt(i)))) ;
{
digit = false;
valid = false;
i++;
}
if (!(password.matches(special))) ;
{
hasspecial = false;
valid = false;
}
if (upper != true) {
System.out.println("Must contain an upper case letter.");
}
if (lower != true) {
System.out.println("Must contain a lower case letter.");
}
if (digit != true) {
System.out.println("Must contain a numeric digit.");
}
if (hasspecial != true) {
System.out.println("Must contain a special character.");
}
if (valid) {
System.out.println("Valid.");
} else if (valid != true) {
System.out.println("Invalid.");
}
}
}
}
One thing. All your if lines are wrong.
You are adding a ';' after the if. That means, if the if condition is met, do nothing, then always execute the following lines.
Another thing, when you do
if (!(password.matches(special))) {
hasspecial = false;
valid = false;
}
You are asking for the password to match the string "!##$%^&(asterisk)", which it probably doesn't. So, since you are assuming that the string contains a special character, hasspecial will always be true. You want to write something like password.matches(".(asterisk)[!##$%^&*].(asterisk)) (Probably escaping some characters).
Finally, you are saying if a letter doesn't meet a condition, set the marker to false. So, if the following letter does meet the condition, the marker will still be false. You should usually approach this kind of problems by assuming that all of the conditions are false and then setting the markers to true once the condition is met.
Note: I wrote (asterisk) instead of *, becasue the text gets highlighted and I don't know how to escape it :(
I want to write a simple java program to check whether keycode matches a set of conditions.
This is what I have so far:
Scanner keycode = new Scanner(System.in);
System.out.println("Input keycode");
String key1 = keycode.nextLine();
do {
if (key1.length() < 6 || key1.length() > 8) {
System.out.println("must be at least 6 letter and max 8 letter");
return;
}
else {
boolean upper = false;
boolean lower = false;
boolean number = false;
for (char c : key1.toCharArray()) {
if (Character.isUpperCase(c)) {
upper = true;
} else if (Character.isLowerCase(c)) {
lower = true;
} else if (Character.isDigit(c)) {
number = true;
}
}
if (!upper) {
System.out.println("must contain at least one uppercase character");
return;
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
return;
} else if (!number) {
System.out.println("must contain at least one number");
return;
} else {
return;
}
}
} while (true);
System.out.println("Input keycode again");
String key2 = keycode.nextLine();
if (key1.equals(key2)) {
System.out.println("keycode matched");
} else {
System.out.println("keycode dont match");
}
The user is prompted to input a keycode.
The program first checks if it is more than 6 characters and less than 8 characters.
It then checks if it contains a lowercase, uppercase and a number.
I want it to allow user to input the password again if he were to make any mistake rather than doing all over again.
If successful, it will ask the user to input keycode again. If the two keycodes don't match,
the user is allowed to try again. After 3 unsuccessful tries, the system will reply with 'keycode mismatch'.
The part I need assistance in is allowing user to input password if it doesn't fit the requirement and password mismatch. When I enter a password less than 6 characters, I get the following output:
must be at least 6 letter and max 8 letter
must be at least 6 letter and max 8 letter
must be at least 6 letter and max 8 letter
must be at least 6 letter and max 8 letter
must be at least 6 letter and max 8 letter
use a loop
boolean flag=false;
while(flag!=true)
{
Scanner keycode = new Scanner(System.in);
System.out.println("Input keycode");
String key1 = keycode.nextLine();
if (key1.length() < 6 || key1.length() > 8) {
System.out.println("must be at least 6 letter and max 8 letter");
}
else
{
flag=true;
}
}
Use a boolean variable say redo. And at every place you have used return, replace it with redo = true. And your while condition should be while(redo), which will run until redo is true, that it, user hasn't entered correct number.
Also, move your input reading line: -
String key1 = keycode.nextLine();
Inside your do-while loop. And also ,reset your redo variable to false in the loop, so that it doesn't remain true forever.
String[] keys = new String[2]; // Since you are reading 2 keys, so size = 2
boolean redo = false;
int count = 0; // To maintain the number of keys read. should stop at count = 2
do {
redo = false;
Scanner keycode = new Scanner(System.in);
System.out.println("Input keycode No: + " + (count + 1));
String key1 = keycode.nextLine();
if (key1.length() < 6 || key1.length() > 8) {
redo = true;
} else {
/** Your remaining code **/
if (!upper) {
System.out.println("must contain at least one uppercase character");
redo = true;
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
redo = true;
} else if (!number) {
System.out.println("must contain at least one number");
redo = true;
} else {
keys[count++] = key1; // Enter a new key in array
}
}
} while (redo || count < 2);
if (keys[0].equals(keys[1])) {
System.out.println("Keys are equal");
}
You should put the line String key1 = keycode.nextLine(); inside the do loop so that the user is queried once every time it is needed. Else, you are just stuck in a loop that will always check the same value again and again.
boolean redo = false;
do {
redo = false;
Scanner keycode = new Scanner(System.in);
System.out.println("Input keycode");
String key1 = keycode.nextLine();
if (key1.length() < 6 || key1.length() > 8) {
redo = true;
} else {
/** Your remaining code **/
if (!upper) {
System.out.println("must contain at least one uppercase character");
redo = true;
} else if (!lower) {
System.out.println("must contain at least one lowercase character");
redo = true;
} else if (!number) {
System.out.println("must contain at least one number");
redo = true;
}
else{
System.out.println("Input keycode again");
String key2 = keycode.nextLine();
if (key1.equals(key2)) {
System.out.println("keycode matched");
} else {
System.out.println("keycode dont match");
}
}
}
} while (redo);
i manage to fit the code inside here , not sure if its the correct method to do so?