问题
i have three boolean value returning from the method , i want to check condition like this :First It will check all the three boolean value
Scenario 1: if locationMatch, matchCapacity, filterMatchStatus then statement return true value.
Scenario 2: if locationMatch, matchCapacity, filterMatchStatus if any boolean is false then it return false value
I tried like this but , it is returning true if any boolean value is true
public boolean matchFilter(FilterTruck filter){
boolean locationMatch = filterMatchesLocation(filter);
boolean matchCapacity = filterMatchesCapacity(filter);
boolean filterMatchStatus = filterMatchesStatus(filter);
if (locationMatch) {
return true;
}
if (matchCapacity) {
return true;
}
if (filterMatchStatus) {
return true;
}
}
return false;
}
回答1:
Updated your code try this.
public boolean matchFilter(FilterTruck filter) {
boolean locationMatch = filterMatchesLocation(filter);
boolean matchCapacity = filterMatchesCapacity(filter);
boolean filterMatchStatus = filterMatchesStatus(filter);
return locationMatch && matchCapacity && filterMatchStatus;
}
回答2:
Replace your code with below code. Use '&' Operator in your case, because '&' will return true, if expression are satisfying the given conditions, otherwise result will be false
public boolean matchFilter(FilterTruck filter){
boolean locationMatch = filterMatchesLocation(filter);
boolean matchCapacity = filterMatchesCapacity(filter);
boolean filterMatchStatus = filterMatchesStatus(filter);
return locationMatch && matchCapacity && filterMatchStatus;
}
回答3:
Remove all the if
conditions and return the following from your method
return (locationMatch && matchCapacity && filterMatchStatus);
回答4:
Similar to the other answers, but in a shorter form (and it has a single exit point!):
public boolean matchFilter(FilterTruck filter)
{
boolean locationMatch = filterMatchesLocation(filter);
boolean matchCapacity = filterMatchesCapacity(filter);
boolean filterMatchStatus = filterMatchesStatus(filter);
return (locationMatch && matchCapacity && filterMatchStatus)
}
回答5:
public boolean matchFilter(FilterTruck filter){
boolean locationMatch = filterMatchesLocation(filter);
boolean matchCapacity = filterMatchesCapacity(filter);
boolean filterMatchStatus = filterMatchesStatus(filter);
return locationMatch && matchCapacity && filterMatchStatus;
}
code minimized. Thank you to @Deepak . Basically you are saying here that only returns true if all 3 variables are true. if one is false, statement returns false (Boolean algebra)
回答6:
Try this code:
public boolean matchFilter(FilterTruck filter){
return filterMatchesLocation(filter) && filterMatchesCapacity(filter) && filterMatchesStatus(filter);
}
来源:https://stackoverflow.com/questions/41036959/compare-multiple-boolean-values