When does Java if statement exit? - java

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

Related

How to stop actor from continuously picking up object?

I'm taking an intro to java class at school and were doing very early on stuff. We are given a few methods and the knowledge of how if else statements, while loops, etc work. We use a program called greenfoot. The objective of the project is to have the character go around and pick up all the leaves, then place them at the end of the row and repeat. The order is changed so you need control statements. I am encountering an issue where at the end of each row, I will place a leaf, then pick it up and loop that forever. I have tried to solve it with variables to no avail. My code is here:
public void rowSweep() {
boolean turnCheck = false;
boolean leafCheck = true;
if (foundLeaf() && (leafCheck)) {
pickLeaf();
leafCheck = true;
}
else if (canMove() && (!facingNorth())) {
walk();
leafCheck = true;
}
else if (hasLeaf()) {
while (hasLeaf()) {
placeLeaf();
leafCheck = false;
}
}
else {
turnLeft();
while (canMove() && (!facingNorth())) {
walk();
turnCheck = true;
}
if (!canMove() && (turnCheck)) {
turnLeft();
walk();
turnLeft();
}
}
}
There are no syntax errors, just it doesn't do it properly. How can I make it so that I can move on after I place it instead of infinitely repeating?

Using a variable that is changed within an if statement

I am writing a program in JAVA where I need to change a boolean, but I am not able to fix it.
The lay out is as follows
while(statement){
Boolean behind = true;
if (behind == true){
do something
behind = false;
}
if (behind == false){
do something else
behind = true;
}
}
So basically my program needs to iterate 'doing something' and 'doing something else'. But I reckon my boolean behind is not changed by the if-statement, since that 'version' of behind only lives within the statement. Any suggestions on how to cope with this?
Do not use var == true/false. This may reduce performance and makes the code unclear. Use var instead of var == true and !var instead of var == false.
Use an else statement instead of checking the condition's opposite.
if (behind) {
//...
behind = false;
} else {
//...
behind = true;
}
3. **Define the boolean outside `while`.**
This also solves your problem because you don't "re-check" the variable.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
}else{
do something else;
behind = true;
}
}
Define the boolean before the while block.
Boolean behind = true;
while(statement){
if (behind){
do something;
behind = false;
} else {
do something;
behind = true;
}
}

Go ahead only if (condition)

I have this code
spinRoullete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (errors()){
something
return;}
if (!errors()){
something else}
And this is for errors
private boolean errors() {
if (Rone.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
} if (Rtwo.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
} else {
nr1.setError(null);
}
if (nr2.getText().length() == 0) {
nr2.setError("");
} else {
nr2.setError(null);
}
}
Something here it's wrong and I don't know what .. The texterrors appears, and disappear when I complete the nr1, or nr2 (edittexts) but something it's wrong with the second if from onClick. When the errors disappear I want to go forward to that second if ( that with something else).. What should I edit to do this?
First off, minor optimization improvement: You have this code (formatted for improved readability, same code):
if (errors()){
something...
return;
}
if (!errors()){
something else...
}
But you don't need that least one since you have a return statement:
if(errors()){
something
return;
}
something else...
The method is called once instead of twice if there isn't an error, so you avoid problems there.
But you never return any visible value from errors(). Most likely, you have return true at the bottom, meaning it always goes into the first if statement. Simply change the method:
private boolean errors() {
boolean i1 = false;//if no errors, return false
if (Rone.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
i1 = true;//There is at least one error
} else {
nr1.setError(null);
}
}
if (Rtwo.isChecked()) {
if (nr1.getText().length() == 0) {
nr1.setError("");
i1 = true;//there is at least one error
} else {
nr1.setError(null);
}
if (nr2.getText().length() == 0) {
nr2.setError("");
return true;//This is the last thing that can happen, so just return true. There is at least one error, this one
} else {
nr2.setError(null);
return i1;//there could have been an error earlier, so return i1
}
}
return i1;//and if the last box isn't checked, return i1 here
}
Most likely, you have return true at the bottom of the method. That means it will always go into the first if-statement and return even if there are no errors.
And you should really start looking into indentation conventions, some of the code you posted is very hard to read because of that

How to break inside if condition in java

i Have below method . which i am calling an boolean method inside it.if that boolean method is true then exit from the block else continue with else block. Below is what i tried. but failed to break the method.
public IStatus validate() throws ExecutionValidationException {
ConfigurationHandler handler = new ConfigurationHandler(getExecutionParameters());
if (handler.isModelValidationEnabled()){
//how to handle here and exit here. i need to continue the application
} else
this.loggerStorage.getLogger().info(VALIDATION_DM_START);
try {
return getDataModel().validateModel();
} finally {
this.loggerStorage.getLogger().info(VALIDATION_DM_FINISHED);
}
}
No need to put anything in the if body, the else is skipped if the if is true. But, It would be cleaner to use a boolean negation like,
public void method1(){
A a = new A();
if (!a.method2()) {
method3(); //<-- block not entered if method2() returns true.
}
}
i need to exit from method1()completely. i don't want to continue else
part.How can i break/exit here... and continue with the application.
If false then execute else part
It is the goal of a if else block.
Here if the if statement is true, the else block is never reached.
if(a.method2() == true){
...
}
else{
...
}
You could use a return statement if you had some other processings after the if statement that you don't want ignore in this specific case.
But in this case you don't need to couple the if where you want to make a return with other else if blocks as they are not dependent:
if(a.method2() == true){
...
return;
}
if(...){
...
}
else{
...
}
// do some processing
You can use;
if(a.method2() == true){
return;
}
But I really think you should question what you're trying to accomplish.
public void method1(){
A a = new A();
if(a.method2() == false){
continue with method3();
}
}

Java nested for related query

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

Categories

Resources