How to break inside if condition in java - 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();
}
}

Related

Using booleans with set and get methods

To summarize I am making a program for a metro ticket system. and I am using set and get methods for it, when it comes to boolean values (since I need to validate that the person enters enough money for the ticket) how am i supposed to put in the main class( it is defined in brain) using the set method and an if statement.Here is a little fraction of the entire code and the rest is on github(https://github.com/alexxei4/subwayticket). The main is basically the class that will be used for interaction with the user and the brain is where alot of the actions are defined.All help is appreciated, please and thank you.
if (Choice1a == 10){
if(subway1.ticketcounter1(true);){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1(false);){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
This is not how you evaluate boolean values, you just place the value in an if statement and it will proceed if true and refuse if false, also there is no need to duplicate the statement when you can just place an else block to handle situations that are not true:
if(subway1.ticketcounter1) {
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
Also do not include semicolons in if statements, that's incorrect syntax. Read more about how to use use boolean values here: https://codingbat.com/doc/java-if-boolean-logic.html
EDIT:
After reading through your Github code I see that ticketcounter1 indeed is a method, but what it's doing is trying to change the value of ticketcounter1 like it's a referenced object, but boolean are primitive data types and can't be referenced, and even if they could it still wouldn't work because Java is a pass-by-value language. Read here for more information on that.
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2){
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
Like the other answer said you should be returning the value as boolean instead of trying to change it:
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
But all in all your code demonstrated fundamental flaws in understanding how the language works, I would suggest picking up a good Java for beginners kind of book or do some introductory online tutorials. Here is a good place to start your learning journey: https://docs.oracle.com/javase/tutorial/java/index.html
You code is like this
public void ticketcounter1(boolean ticketcounter1){
if (credit1 > total1){
ticketcounter1 = true;
}
else {
ticketcounter1 = false;
}
}
public void ticketcounter2(boolean ticketcounter2) {
if (credit2 > total2){
ticketcounter2 = true;
}
else {
ticketcounter2= false;
}
}
It should be like this. Instead of using the variable and passing it though parameter. Use getter. Besides that your code won't run since subway1.ticketcounter1(true) is giving nothing. It is only changing variables stored in Brain.java. No information is being sent to main.
public boolean ticketcounter1(){
if (credit1 > total1){
return true;
}
else {
return false;
}
}
public boolean ticketcounter2(){
if (credit2 > total2){
return true;
}
else {
return false;
}
}
You can create functions without parameters. I don't know what were you trying to do?
if (Choice1a == 10){
if(subway1.ticketcounter1()){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
}
if(subway1.ticketcounter1()){
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
subway1.ticketcounter1() will give either true and false. Do not use ; in if statement condition. ; ends the statement. Check this guide to learn about use of semi-colon If you do want to use ; The code should look like this
if (Choice1a == 10){
boolean ticketCounter1 = subway1.ticketcounter1();
if(ticketCounter1){
System.out.println("PRINT SUCCESSFUL, COLLECT YOUR TICKET!");
} else {
System.out.println("INSEFFICIENT FUNDS, PLEASE ADD MORE");
}
}
P.S You don't need two ifs if-else would be better in this case
if(condition) {
// Conditions is true
} else {
// Condition is false
}

When check if method true, the method is called again?

Ok so in my program I have two classes, LinkPhone.java, and Frame.java. In the LinkPhone part it calls a function to determine if it is true, and then if it is do something. But then I call the function and use an If statement to check it, it recalls the statement from the If statement. Like in the console it says "DEBUG: Frame init success" twice. Why does it call the function twice and how would I fix it?
LinkPhone.java:
Frame.initFrame();
if(Frame.initFrame() == true){
return;
} else {
return;
}
Frame.java:
public static boolean initFrame(){
try {
JFrame frame = new JFrame("Link Phone");
System.out.println("DEBUG: Frame init success");
return true;
} catch (Exception e) {
System.out.println("DEBUG: Frame init failed!!!");
return false;
}
}
You're calling your method twice!
Frame.initFrame();
if(Frame.initFrame() == true){
return;
} else {
return;
}
Just call it once:
// Frame.initFrame(); // no need for this one
if(Frame.initFrame()){
// hopefully you do more in here!
// return;
} else {
// hopefully you do more in here!
// return;
}
return;
Some side notes:
I would avoid calling a class "Frame" since that would clash with a class that is part of the Java core classes. Give it a more descriptive name to avoid future problems.
It looks like you're calling static methods. This is OK if indicated, but over-use of static methods and variables risks increasing the connectedness of your program, i.e., it can increase code coupling, something that in larger programs can lead to increased complexity and risk of bugs. Java is an OOP language for a reason, since proper use of OOP techniques helps hide data, reducing bugs and increasing code re-use.
Both of your if and else code blocks have a return call. Better to simplify the code and get the return calls out of the blocks. Simply call return after the both blocks.
Again hopefully your if and else blocks hold more code than just matching return statements.
You need to keep hold of the result from the first time you call the method:
boolean result = Frame.initFrame();
if(result) {
return;
} else {
return;
}
Yes. Every time your program executes Frame.initFrame() it calls the method. (That's what the () syntax means)
If you want to call it once you can do this (without the extra call before it):
if(Frame.initFrame() == true) {
or this, if you prefer having the method call on a separate line:
boolean result = Frame.initFrame();
if(result == true) {
It's called twice because you write Frame.initFrame() twice.
Frame.initFrame(); //Once
if(Frame.initFrame() /* Twice */ == true){
return;
} else {
return;
}
If you only meant to call it once and want to store the result, try this:
boolean ok = Frame.initFrame();
if(ok){ //Use result of call
//Do stuff in the event the initting went correctly
return;
} else {
//Do stuff in the event the initting failed
return;
}
Or, event more compactly:
if(Frame.initFrame()){ //Use result of call
//Do stuff in the event the initting went correctly
return;
} else {
//Do stuff in the event the initting failed
return;
}

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

Breaking Out Of A Loop Using A Method In Java

I am trying to use a method to double check before a user exits a while loop in my program.
private static Scanner input = new Scanner(System.in);
public static void ays() {
System.out.println("Are you sure?");
String ays = input.nextLine();
if (ays.equals("Yes")) {
break;
} else {
continue;
}
}
Upon running the program, I get the error break outside switch or loop, and continue outside switch or loop. Is there any way to achieve my goal here?
I guess you are invoking ays() inside a while loop. Let the return type of ays() be boolean and let it return either true or false. Invoke ays() from inside the while loop and based on the value returned by ays(), you continue or break out of the loop.
while (true) {
//Do Something
if (ays()) {
continue();
} else {
break();
}
}

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