Java nested ifs - java

Below is a small function which when given two numbers (a, b), returns true if one of the numbers is a teen-number. Returns false if both are teen. Returns false if both are not teen. I failed these test cases but I can't figure out why. Help?
(13, 99), (14, 20), and (16, 9)
public boolean loneTeen(int a, int b)
{
if(a<=19 && a>=13)
{
if(b<=19 && b>=13)
{
return false;
}
}
else if(a<=19 && a>=13)
{
return true;
}
else if(b<=19 && b>=13)
{
return true;
}
return false;
}

All three test cases will enter first if branch, they will not match inner condition and, since they already matched first branch, will not match any of else if's. So, they will all return false which is wrong.

Using a small auxiliary method can make your life much easier (and the code more readable!):
private boolean isTeen(int a) {
return a > 12 && a < 20;
}
public boolean loneTeen(int a, int b) {
if(isTeen(a) && isTeen(b) ||
!isTeen(a) && !isTeen(b)) {
return false;
}
return true;
}

First else won't be executed as you are putting the same condition on both if and else.try putting
if( a>=13 && a<=19 && b>=13 && b<=19){return false;}
else if(a>=13 && a<= 19){return true;}
else if(b<=19 && b>=13){return true;}
else return false;

Related

Multiple boolean values in if else statement is always false in Java

I am stuck to this method because of the if else condition says that
Condition usersInSales && usersInPayments is always false
Condition usersInSales && usersInLoans is always false
Condition usersInPayments && usersInLoans is always false
I tried different condition combinations and added the false values to try resolve it but it didn't help. Please can I have some help? Thanks in advance
private List<UserResource> usersFilteredByDepartment(List<UserResource> users, boolean usersInSales, boolean usersInPayments, boolean usersInLoans) {
if (usersInSales) {
return getUsersInSales(users);
} else if (usersInPayments) {
return getUsersInPayments(users);
} else if (usersInLoans) {
return getUsersInLoans(users);
} else if (usersInSales && usersInPayments) {
return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInSales && usersInLoans) {
return Stream.concat(getUsersInSales(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInPayments && usersInLoans) {
return Stream.concat(getUsersInPayments(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList());
} else return users;
}
You have two solutions.
Reorder your conditions, as others have shown. In your code by time you hit the && statements you have already dealt with the cases when one half is true. The && (two clauses) is more restrictive than a single clause.
Alternatively, put the double clauses inside the previous ifs.
if (usersInSales) {
return getUsersInSales(users);
} else if (usersInPayments) {
return getUsersInPayments(users);
} else if (usersInLoans) {
return getUsersInLoans(users);
} else if (usersInSales && usersInPayments) {
return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInSales && usersInLoans) {...
becomes
if (usersInSales) {
if (usersInPayments) { // Nested if is like && operator.
return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList());
} else {
return getUsersInSales(users);
}
} else if (usersInPayments) { ...
This is a little more efficient and I think generally preferable.
if (usersInSales) {
return getUsersInSales(users);
} else if (usersInPayments) { ---> You get here when userInSales = false
return getUsersInPayments(users);
} else if (usersInLoans) { --> You get here when usersInSales = false && usersInPayments = false
return getUsersInLoans(users);
} else if () { --> You get here when usersInSales = false && usersInPayments = false && usersInLoans = false. No use in comparing what you compare here. It will be always false as it reports to
}
Hope you now can figure your way out
You could try to check first the most specific constraints and then in the end move to more general constraints.
if (usersInSales && usersInPayments) {
return Stream.concat(getUsersInSales(users).stream(), getUsersInPayments(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInSales && usersInLoans) {
return Stream.concat(getUsersInSales(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInPayments && usersInLoans) {
return Stream.concat(getUsersInPayments(users).stream(), getUsersInLoans(users).stream()).distinct().collect(Collectors.toList());
} else if (usersInSales) {
return getUsersInSales(users);
} else if (usersInPayments) {
return getUsersInPayments(users);
} else if (usersInLoans) {
return getUsersInLoans(users);
} else return users;
Checking your workflow however IMO your method would have more sense without all those if, else checks. Just this could be enough
private List<UserResource> usersFilteredByDepartment(List<UserResource> users, boolean usersInSales, boolean usersInPayments, boolean usersInLoans) {
return Stream.concat(
usersInPayments? getUsersInPayments(users).stream(): Stream.empty(),
usersInLoans? getUsersInLoans(users).stream(): Stream.empty(),
usersInSales? getUsersInSales(users).stream(): Stream.empty()
).distinct().collect(Collectors.toList());
}
Consider your logic: you first check usersInSales, and return if it's true. Then you check usersInPayments and return if it's true. So when you then check usersInSales && usersInPayments, both will be false because you already handled the cases when either of them are true.
You need to change your logic so you handle the conditions additive instead of exclusively.
your last 3 conditions will never run. because one of your first 3 conditions will already be true. To fix this you need to reverse the order of your conditions, try this:
if (usersInSales && usersInPayments) {
} else if (usersInSales && usersInLoans) {
} else if (usersInPayments && usersInLoans) {
} else if (usersInSales ) {
} else if ( usersInLoans) {
} else if (usersInLoans) {
} else return users;

Return multiple values from void and boolean methods

I have the following problem: Having a boolean static method that computes similarity between two integers, I am asked to return 4 results:
without changing the return type of the method, it
should stay boolean.
without updating/using the values of external variables and objects
This is what I've done so far (I can't change return value from boolean to something else, such as an int, I must only use boolean):
public static boolean isSimilar(int a, int b) {
int abs=Math.abs(a-b);
if (abs==0) {
return true;
} else if (abs>10) {
return false;
} else if (abs<=5){
//MUST return something else, ie. semi-true
} else {
//MUST return something else, ie. semi-false
}
}
The following is bad practice anyway, but If you can try-catch exceptions you can actually define some extra outputs by convention. For instance:
public static boolean isSimilar(int a, int b) {
int abs = Math.abs(a-b);
if (abs == 0) {
return true;
} else if (abs > 10) {
return false;
} else if (abs <= 5){
int c = a/0; //ArithmeticException: / by zero (your semi-true)
return true;
} else {
Integer d = null;
d.intValue(); //NullPointer Exception (your semi-false)
return false;
}
}
A boolean can have two values (true or false). Period. So if you can't change the return type or any variables outside (which would be bad practice anyway), it's not possible to do what you want.
Does adding a parameter to the function violate rule 2? If not, this might be a possible solution:
public static boolean isSimilar(int a, int b, int condition) {
int abs = Math.abs(a - b);
switch (condition) {
case 1:
if (abs == 0) {
return true; // true
}
case 2:
if (abs > 10) {
return true; // false
}
case 3:
if (abs <= 5 && abs != 0) {
return true; // semi-true
}
case 4:
if (abs > 5 && abs <= 10) {
return true; // semi-false
}
default:
return false;
}
}
By calling the function 4 times (using condition = 1, 2, 3 and 4), we can check for the 4 results (only one would return true, other 3 would return false).

Method always returns true?

I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.
I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses

unable to find problems with this piece of code

I have this piece of code, I think I have all the braces covered. Still getting braces not closed error. When I put more braces, then gives me something else. Can you anybody tell me what I am doing wrong here?
public static boolean isValid(int day, int month, int year)
{
if (year < 1900)
{
return false;
}
else {
if (month>0 && month<13)
{
if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
{
return day > 0 && day <=31;
}
else if (month==4 || month==6 || month==9 || month==11)
{
return day>0 && day<=30;
}
else if (month==2)
{
if (isLeap(year))
{
//(d= 29);
return day>0 && day <=29;
}
else {
return day>0 && day<= 28;
}
}
}
}
}
}
Because of your if-else conditions it may not be able to return a boolean value.That is the problem.Check your code's logic.
I don't think you are missing any braces but you are not returning values for every possible execution path.
if you put a return false at the bottom of the function it will compile.
Little tip, to save the reader all of those nested ifs and braces:
if(day>0 && day<= 28){
return true;
else{
return false;
}
you can do this:
return day > 0 && day <= 28;
if you're using eclipse use ctrl shift f to balance braces easier to read and see if you miss one or need one

Combine 2 Boolean statements to make another one

I am trying to combine two boolean statements in order to validate a number.
This is the code for the two functions:
public boolean numberOne(String number)
{
int a = Integer.parseInt(number);
if(a >= 0 && a <= 7 && number.length() <= 1) {
return true;
}
else {
return false;
}
}
public boolean numberTwo(String number)
{
int b = Integer.parseInt(number);
if(b >= 01 && b <= 15 && number.length() <= 2) {
return true;
}
else {
return false;
}
}
Now I want to create another Boolean function to validate this number when both combined e.g. 215 would be true and 645 would be false.
How can I do this?
Thanks
Two changes. The first is a side note. This code
if (long_test) {
return true;
} else {
return false;
}
should be rewritten as this:
return long_test;
The other change described by dampee once he gets his variable names to match.
Ok. So you want to split the string and have the first number of the string compared to the first function and the last two numbers compared to the second function?
public boolean numberThree (String number) {
String part1 = number.substring(0, 1);
String part2 = number.substring(1);
return numberOne(part1) && numberTwo(part2);
}

Categories

Resources