Reputation: 43
It keeps skipping the else part of my statement. I just want it to print out of the invalid line if all the other restrictions are not met.
import java.util.Scanner;
public class Program_3
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a password: ");
String str = input.nextLine();
boolean lowerCase = false;
boolean upperCase = false;
boolean number = false;
char y;
for (int i = 0; i < str.length(); i++)
{
y = str.charAt(i);
if(Character.isUpperCase(y))
{
upperCase = true;
}
else if(Character.isDigit(y))
{
number = true;
}
else if(Character.isLowerCase(y))
{
lowerCase = true;
}
}
if (lowerCase == true)
{
if (upperCase == true)
{
if (number == true)
{
if (str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
}
}
}
else
System.out.println("Verdict:\t Invalid");
}
}
why does it skip and not print the invalid line when all ifs are not met?
Upvotes: 1
Views: 2344
Reputation: 1709
Your test password contains at least one lowercase character. As long as it does, the else statement will never execute. To test "if all conditions are true ... else ..." try the follwing:
if (lowerCase && upperCase && number && str.length >= 8) {
// password ok
} else {
// password not ok
}
By the way, as you can see I don't use lowerCase == true since it's not needed, lowerCase already is a boolean.
Upvotes: 0
Reputation:
This code can b be simplified to show control-flow:
if(lowerCase == true)
{
//lowerCase == true -> execute this code
if( upperCase == true)...
}else
//lowerCase == false -> execute this code
...
The inner if-statements (which are exclusive btw.) don't execute the outer else
-statements, if the condition is false. The logical correct version of your code would be:
if(lowerCase && upperCase && isNumber && str.length() > 8)
System.out.println("Verdict:\t Valid");
else
...
Upvotes: 2
Reputation: 27565
The else
in your code relates only to the outermost if
.
So it will only be executed if lowerCase == false
.
To fix this logic, combine all three conditions in a single if
, i.e.:
if (lowerCase == true && upperCase == true && number == true && str.length() >= 8)
{
System.out.println("Verdict:\t Valid");
}
else
System.out.println("Verdict:\t Invalid");
Side note, booleans don't require explicit comparison to true
, so you can write it shorter:
if (lowerCase && upperCase && number && str.length() >= 8)
Upvotes: 5
Reputation: 236114
The else
condition is placed in the wrong place, it'll only be reached if the lowerCase
condition is false
. And anyway, we can simplify and combine all the if
s in a single condition, what you meant to say was this:
if (lowerCase && upperCase && number && str.length() >= 8) {
System.out.println("Verdict:\t Valid");
} else {
System.out.println("Verdict:\t Invalid");
}
Upvotes: 2