Every now and then there is a need to store a boolean value only once (to record that it has changed from false to true or vice versa) in a loop, while executing the loop to the end but not caring anymore about changes in the boolean value. Example:
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean result = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (!dbDelete) {
result = false;
}
}
return result;
}
Is there some way to execute the equivalent of the code
if (!dbDelete) {
result = false;
}
or
if (!dbDelete && !result) {
result = false;
}
in a more elegant way, preferrably in one line?
How about:
result &= dbDelete(object);
This is equivalent to:
result = result & dbDelete(object);
So it will only be true if result was previously true and dbDelete returned true.
if (!dbDelete(object)) {
result = false;
}
result = dbDelete(object) ? result : false;
Try putting more meaning into your variable names - it makes things easier.
public static boolean dbDelete(Collection argObjectCollectionToDelete) {
boolean completedSuccessfully = true;
for (Object object : argObjectCollectionToDelete) {
boolean dbDelete = dbDelete(object);
if (completedSuccessfully && !dbDelete) { //won't change anymore after failure
completedSuccessfully = false;
}
}
return completedSuccessfully;
}
Related
Hello I am very new to Java, I wanted to know if it were possible to pass a character to a method, and then return true if this character is valid.
I have this method:
public void btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// Change button color
}
}
What I would like is to have something like this, although it won't let me do this:
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
}
}
So it takes a character variable c and returns true if valid. Is there a best practice for this sort of thing?
You can do something like this in order to always return some value. This should be possible and acceptable with Java.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true; // this will return in case of your condition is true
}
return false; // this will return otherwise.
}
try this single line
public boolean btnColor(char c, boolean b) {
return hm.getHiddenWordUpdated().contains(String.valueOf(c));
}
It'll return true or false.
When you have public boolean methodName, it means it MUST return a boolean. Having an "IF" statement in your code, means it can split up to a two possible ways: IF-true and IF-false. You have declared the true statement:
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
So you are covering 1/2 of the solution. But what if it is false ? Nothing ? This is why you have problems, so to solve your problem you code should looks like this:
public boolean btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
} else {
return false;
}
Now if it is containing the character - it returns TRUE, but if it is not containing it returns FALSE.
All code paths need to return a value.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// add additional code
return true;
}
return false;
}
Alternatively, you could use conditionals in a single line:
public boolean btnColor(char c) {
return (hm.getHiddenWordUpdated().contains(String.valueOf(c))) ? true:false;
}
I need to set boolean value only when all the conditions are set. I am struggling to set the boolean value inside the for loop. As per my code the value is set TRUE/FALSE based on last item in the list. But the value should set only when all conditions are set. Could someone help me on this?
boolean validateName(List<String> NameList, Name name) {
boolean value = false;
for (String name : NameList) {
name.hasName(name);
value = true;
}
return value;
}
Try this:
boolean validateName(List<String> nameList, Name name) {
for (String nameTmp : nameList) {
if(!nameTmp.equals(name))
return false;
}
return true;
}
Return false as soon as one condition is not met.
boolean validateName(List<String> NameList, Name aName) {
boolean value = false;
for (String name : NameList) {
if(!aName.hasName(name))
return false;
}
return true;
}
Try this if you are using Java 8:
return NameList.stream().allMatch(element -> element.equals(name))
Why the following method always return false for the below value.
Do I confuse with somethings??
public boolean isTwoWay(Detail detail) {
return (detail.isExchange && detail.isTwoWay && !detail.isIVR);
}
which data contain following
detail.isExchange = true;
detail.isTwoWay = true;
detail.isIVR = false;
but it return false instead of true
The only way the method will return false is if one of your assumptions is wrong:
detail.isExchange = true;
detail.isTwoWat = true;
detail.isIVR = false;
Rest assured, this kind of oversight happens to programmers all the time, including the best of us.
Put a breakpoint where you receive false instead of your expected true, and verify your assumptions.
I have tried with that and its print true always.
boolean isExchange = true;
boolean isTwoWay = true;
boolean isIVR = false;
System.out.println(isExchange && isTwoWay && !isIVR);
I am writing a Data Acquisition Software using Sparrow's platform Kmax. This platform has it's own classes and methods, that one has to have worked with it to be familiar. I am trying to make a checkbox button to do a job. To do that, I need to convert a string 1 or 0 to boolean true or false respectively. For this task I built the simple method that follows
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
}
When I am trying to compile it I get an error
Runtime.java:30: error: missing return statement }
Note that line 30 is the last line(i.e. } ) of the previous code.
I don't see any point on what could be wrong. Any ideas?
Say those cases aren't true (that s is not equal to "1" or "0"), then what? You must return a default value at the end (which doesn't seem to be a good idea for your code if you are only expecting those two values) or throw an Exception:
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;
}
if (s.equals("0")){
return false;
}
throw new Exception("0 or 1 Required");
}
There needs to be a return statement executed in all cases, but you don't have a return statement if both if statements are false.
Provide a default case at the end:
return true;
}
The compiler does not know that your String will always be "1" or "0". Therefore, as a safety measure, it ensures that you are required to return some value (although you may never actually return it in practice).
I suggest you return false by default.
public static boolean stringToBool(String s) {
if (s.equals("1")){
return true;}
if (s.equals("0")){
return false;}
return false;
}
You have several options. You code cannot compile because your code must have a return statement always, but, when you put it within the if statemens the compiler cannot find a return for every possible execution path.
public static final String TRUE = "1";
public static final String FALSE = "0"
public static boolean stringToBool(String s) {
boolean result = false;
if (s.equals(TRUE)){
return true;
}
return result;
}
public static boolean stringToBool2(String s) {
boolean result = false;
switch(s) {
case FALSE:
result = false;
break;
case TRUE:
result = true;
break;
default:
// Uuups. Throw exception or return false
}
return result;
}
I am newbie in java.
Here is my code:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
else return false;
}
but compiler gives:
Error: public boolean endsLy(String str) {
This method must return a result of type boolean
Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider adding a last line in the method return some_value;
so a value is always returned.
You are not handling the branch where (str.length()>=2, but !str.substring(str.length()-2).equals("ly"). Remove the else from the final return statement:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly")) return true;
}
return false;
}
An even simpler alternative (also less prone to the kind of error you are having), is to have only a single return statement:
public boolean endsLy(String str) {
return str.length()>=2 && str.substring(str.length()-2).equals("ly");
}
Or simply :
public static boolean endsLy(String str) {
return str.length()>= 2 && str.substring(str.length()-2).equals("ly");
}
You might also check if the String is not null.
return str != null && str.length()>= 2 && str.substring(str.length()-2).equals("ly");
here a correction:
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
else
return false;
}
else{
return false;
}
}
This error means that there might be a possibility that the function will not return anything under some circumstances.
so if this condition => if(str.length()>=2) stands true the code will enter into it. Now if this condition is false => if(str.substring(str.length()-2) the function will have nothing to return. So this is a wise thing that the error prompted.
This means that not all conditions in this function return a bool value. There is a chance that conditions may occur when function does not have anything to return.
because you do not have a boolean value is returned in case !str.substring (str.length () -2). equals ("ly")
if you want to check that your chain is composed of four characters in the last two are "ly" you can use the following codes:
public boolean endsLy(String str) {
if (str.length() == 4 && str.endsWith("ly"))
return true;
return false;
}
Avoid multiple false return statement as return value is true only for condition if(str.substring(str.length()-2).equals("ly")). Following code is for reference.
public boolean endsLy(String str) {
if(str.length()>=2){
if(str.substring(str.length()-2).equals("ly"))
return true;
}
return false;
}