Java nested for related query - java

Why isn't this structure acceptable? Anyway it returns a boolean value right??
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
}

It's not valid because there is a possibilty where nothing is returned. Your method is declared as returning a boolean value, so it MUST return a boolean value at some point in the code before the method is finished, regardless of the inner logic. If your if-statement if (condition) is false, the method doesn't have another return statement, so the code won't even compile. To fix this, add a "default" return value:
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}

Not valid because you need to do a return some default value (return) .
What if conditions not satisfied ??
valid is :
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
As a side note,To make your code mode readable,I suggest
if(condition && condition && condition)
{
return true;
}
return false;
Prefer to read jls-14.17

Though the method returns true when the condition is satisfied, it doesn't specify a return value when the condition isn't satisfied. The method should cover all the code paths (read conditional statements).

As the answers above correctly state, you absolutely have to return something in Java. C doesn't really care.
In order to avoid this I would recommend decreasing the level of nesting to do something like
boolean value=false; //default return
if(cond && cond)
return value;
if(cond)
return false; //if you want to be more specific
if(cond)
value=true;
return value;
so a value gets returned no matter what. On the plus side, readability increases

Related

Java - Passing a char variable to a method and returning a boolean?

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;
}

"Missing return statement" within if / for / while

I have a question regarding return statements used within if() while() or for() statements.
As you can see in the following method, it is expecting that I return a String value. The problem is that if I were to use a return statement within my if statement block, the compiler would return the error missing return statement.
public String myMethod()
{
if(condition)
{
return x;
}
}
Of course I could change the method header to void and use System.out.println instead of return. But is this the right way to do it? Am I missing something?
If you put a return statement in the if, while or for statement then it may or may not return a value. If it will not go inside these statements then also that method should return some value (that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.
But if you write an if / else block and each one of them is having a return in it then the compiler knows that either the if or else will get executed and the method will return a value. So this time the compiler will not force you.
if(condition)
{
return;
}
else
{
return;
}
That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function return? The compiler needs to know what to return in every possible execution of your function.
Checking Java documentation:
Definition: If a method declaration has a return type then there must
be a return statement at the end of the method. If the return
statement is not there the missing return statement error is thrown.
This error is also thrown if the method does not have a return type
and has not been declared using void (i.e., it was mistakenly
omitted).
You can do this to solve your problem:
public String myMethod()
{
String result = null;
if(condition)
{
result = x;
}
return result;
}
That is illegal syntax. It is not an optional thing for you to return a variable. You must return a variable of the type you specify in your method.
public String myMethod()
{
if(condition)
{
return x;
}
}
You are effectively saying: I promise any class can use this method (public) and I promise it will always return a String (String).
Then you are saying IF my condition is true I will return x. Well, that is too bad. There isn't any IF in your promise. You promised that myMethod will always return a String.
Even if your condition is always true, the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions just in case all of your conditions fail.
public String myMethod()
{
if(condition)
{
return x;
}
return ""; // Or whatever the default behavior will be if all of your conditions fail to return.
}
Try with, as if the if condition returns false, so it will return empty, otherwise nothing to return.
public String myMethod()
{
if(condition)
{
return x;
}
return ""
}
Because the compiler doesn't know if any of those if blocks will ever be reached, so it's giving you an error.
You have to add a return statement if the condition is false.
public String myMethod() {
if(condition) {
return x;
}
// if condition is false you HAVE TO return a string
// you could return a string, a empty string or null
return otherCondition;
}
FYI:
Oracle docs for return statement
This will return the string only if the condition is true.
public String myMethod()
{
if(condition)
{
return x;
}
else
return "";
}
Anyhow, myMethod() should return a String value. What if your condition is false? - is myMethod returning anything? The answer is no, so you need to define return null or some string value for the false condition:
public String myMethod() {
boolean c = true;
if (conditions) {
return "d";
}
return null; // Or some other string value
}

Missing return statement in Java/Kmax

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;
}

My method can't return boolean

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;
}

When does Java if statement exit?

I have a function when has an if-else statement. It essentially looks like this:
if(boolean == true)
{
// do something
boolean = false;
}
else if(boolean == false)
{
// do the other thing
boolean = true;
}
Now, my understanding is that the if statement will exit and return control to the function and then continue according to the changed boolean value. But I'm clearly missing something because my code is not exiting the original 'if'/'else if' statement (whichever the original case). Can anyone tell me what I've missed?
Well as requested, additional data about the code is that it is a part of my android project and each condition in the if-else block has a nested function and the boolean(global) value is being set/unset withing these functions. So the code now looks like this:
dummyFunction(){
boolean = checkIfTrueOrFalse();
if (boolean) {
onClick( public void onClick(){
// do something
boolean = false;}
} else if(boolean == false){
onClick( public void onClick(){
// do something
boolean = true;}
}
}
Any ideas?
if(boolean == true)
{
// do something
boolean = false;
}
if (boolean == false)
{
// do the other thing
boolean = true;
}
When you do this, then the program will flow to the second condition. In an if/else if statement, if the if statement has been satisfied, then the program will ignore the else if block.
Your current code simply flows through the first if block and then skips the else if statement to end the block.
void someMethod()
{
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
}
else if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
}
When someMethod will execute, since aBoolean is assigned with true, control will come to if block cause the condition becomes true. if it was false, then the control will come to else part.
We have many good answers/comments already but just wanted to add something here -
1.
if (condition) {
} else {
}
is a single code construct. The condition will be evaluated at the beginning at run time and java will decide which block to execute i.e. the if block or the else block. Only 1 of the 2 can be executed.
Java allows us to nest if/else. That means we can have something like below -
if(condition1){
} else if (condition2) {
} else if (condition3) {
} else {
}
It is effectively same as below -
if (condition1) {
} else {
if (condition2) {
} else {
if (condition 3) {
} else {
}
}
}
Here, it should be noted that only the block which satisfies the condition will be executed. If none of the conditions is met, then the inner most else will be executed (i.e. the else block of condition3 )
Finally, I feel that your confusion is between the below blocks
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
} else if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
VS
boolean aBoolean = true;
if(aBoolean == true)
{
// do something
aBoolean = false;
}
if(aBoolean == false)
{
// do the other thing
aBoolean = true;
}
In the latter of the 2 examples, there are 2 independent if blocks and both will get executed (off course, this is not logically correct but it is a legal java code.)
Could you provide more info regarding your code not exiting either of the 2 blocks? Doing System.out.println() of variables within your blocks might be able to help you determine why your code is not exiting.
You could use an if/else pair instead of an if/else-if as the parameter that your code depends on is would be either true/false. If the if-block is not satisfied, automatically the else-block would be traversed.
Your code is actually a shortcut for
if (boolean) {
// do something
boolean = false;
} else {
if (!boolean) {
// do the other thing
boolean = true;
}
}
Written this way, it maybe becomes clearer that the inner if nested in the else case will not be processed if the first if condition was already met.
Well I've solved it (taking inputs from here of course). I just added a call to the function within the nested functions and it worked. Now the code looks like this:
public static void dummyFunction(){
boolean = checkIfTrueOrFalse();
if (boolean) {
onClick( public void onClick(){
// do something
dummyFunction();
boolean = false;}
} else if(boolean == false){
onClick( public void onClick(){
// do something
dummyFunction();
boolean = true;}
}
}

Categories

Resources