Is it possible to mid while loop, return to the beginning of the loop?
Something like this
while(this is true)
{
do stuff...
if(this is true)
{
restart while loop;
}
}
Adding clarity: I did not mean restart as in reset variables, I mean restart in the sense of stopping execution and going on to the next iteration.
the continue keyword will do that
while(this is true)
{
do stuff...
if(this is true)
{
continue;
}
}
Basically, continue stops execution of the loop on the spot, and then goes on to the next iteration of the loop. you can do this with other loops such as for loops too.
Yes it is possible. Java provides labels for loops or statement blocks and it must precede a statement.
Syntax is identifier:
START: while(this is true)
{
do stuff...
if(this is true)
{
continue START;
}
}
There are many more ways to do this but i consider this the simplest method.
[EDIT] Misunderstood the question! This works if you want to restart the loop.
There are many ways you can do it. You can have the while loop in a function and call the function. Such as:
public static void loop(){
while(this is true) {
do stuff...
if(this is true) {
loop();
break; <-- dont forget this!
}
}
}
Related
If the code faced a specific case I want to stop the current execution but continue the parent loop.
main() {
while(line not empty) {
// blablabla
method1()
// tadatadatada
}
}
method1() {
// blablabla
method2()
// etcetcetc
}
method2() {
// blablabla
if (var == 1)
stop the execution of the current method and parent method
// etcetcetc
}
In the case explained below, if var == 1, all etcetcetc part of code must not be executed, but tadatadatada must be...
So I want to stop all children executions.
Is there a solution to do that in Java?
Return a value from method2 and check it in method1. If it meets a condition, return from method1 too.
Something like:
method1() {
var shouldBreak = method2();
if (shouldBreak) {
return
}
// more stuff
}
Look into Java Multithreading. This will allow you to run multiple methods simultaneously and give you full control over when to stop a specific thread.
Here's a starting point from another: Threads in Java
I don't quite understand fully what you're asking as your example doesn't have extensive clarity, but hopefully this is what you're looking for.
I have looked in the Javadoc but couldn't find information related to this.
I want the application to stop executing a method if code in that method tells it to do so.
If that sentence was confusing, here's what I want to do in my code:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
So if the boolean condition is true, the method onClick has to stop executing further code.
This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).
return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
There are two way to stop current method/process :
Throwing Exception.
returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
You can just use return to end the method's execution
Either return; from the method early, or throw an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
I think just using return; would do the job
I am using a Do While loop but i have to test whether that condition is met half way through the loop so that if it is met it will skip that part. Is there an efficient way of doing this?
e.g. I currently have something like this:
do {
method1;
if (!condition)
method2;
} while (!condition);
EDIT: I apologise, i don't think i made it clear in the first place. The condition starts as being false, and at some point during the loop one of the methods will set the (global) "condition" to true at which point i want the loop to immediately end. I just think it's messy having to test the ending condition of the loop within it and was wondering if there was anything obvious i was missing.
Please provide more info about methods. If you can return condition from method1/2, then try:
do {
method1;
} while (!condition && !method2)
or if you pass by reference and method return always true:
while (method1 && !condition && method2 && !condition);
or:
while (!method1 && !method2);
EDIT: if:
public boolean method1/2 { ... logic ... ; condition = true; return condition;}
it's hardly depend on what you will do.
I assume that your are looking for is avoiding this additional test for efficiency because "condition" is not met most of the time (1 out of many)...
This optimization may be done by going deeper into what is really done in method1 and method2 (or on the data they are handling) and add a first "fake step" outside of the loop that will disable treatment of method2 only the first time. Would look like this:
prepare_for_loop_entering
do {
method2
method1;
} while (!condition);
if condition is the same on all the places you refer to it than
do {
method1;
method2;
} while (!condition);
as in your while loop condition will always be false (!condition will be true) unless you set it to true in method1; than you can just break; as soon as you set it to true in method1;
How about this:
method1;
while (!condition) {
method2;
method1;
}
what about this:
while (!condition) {
method1;
if(!condition)
method2;
}
How about the code below:
if(condition)
break;
Use the most generic form of a loop:
while (true)
{
method1;
if (!condition) break;
method2;
}
Further explanation
A while loop with a condition "condition" is exactly like:
while (true)
{
if (condition) break;
method1;
method2;
}
And a do-while is exactly like:
while (true)
{
method1;
method2;
if (condition) break;
}
We want neither of those, hence the code above.
if (myCondition1 && myCondition2 && myCondition3)
{
...
}
I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea?
thank u
"Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.
Dead code means it is never going to execute. E.g.
void someMethod() {
System.out.println("Some text");
return;
System.out.println("Another Some text"); // this is dead code, because this will never be printed
}
Same in case of your condition checking e.g.
String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate
}
Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.
If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.
This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:
boolean condition1 = true;
boolean condition 2 = !condition1;
if(condition1 && condition2) {
//This code is all dead
Foo f = fooFactory();
f.barr(new Bazz());
}
Or you unconditionally leave the if block using something like return, break or continue, as shown below:
for(Foo f : foos) {
if(true) {
f.barr(new Bazz());
break;
//Everything after here is dead
System.out.println("O noes. I won't get printed :(");
}
}
Is there a way to break out of a while loop before the original condition is made false?
for example if i have:
while (a==true)
{
doSomething() ;
if (d==false) get out of loop ;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
}
Is there any way of doing this?
Use the break statement.
if (!d) break;
Note that you don't need to compare with true or false in a boolean expression.
break is the command you're looking for.
And don't compare to boolean constants - it really just obscures your meaning. Here's an alternate version:
while (a)
{
doSomething();
if (!d)
break;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true();
}
Try this:
if(d==false) break;
This is called an "unlabeled" break statement, and its purpose is to terminate while, for, and do-while loops.
Reference here.
break;
Yes, use the break statement.
while (a==true)
{
doSomething() ;
if (d==false) break;
doSomething_that_i_don't_want_done_if_d_is_false_but_do_if_a_and_d_are_true() ;
}
while(a)
{
doSomething();
if(!d)
{
break;
}
}
Do the following
Note the inclusion of braces - its good programming practice
while (a==true)
{
doSomething() ;
if (d==false) { break ; }
else { /* Do something else */ }
}
while ( doSomething() && doSomethingElse() );
change the return signature of your methods such that d==doSomething() and a==doSomethingElse(). They must already have side-effects if your loop ever escapes.
If you need an initial test of so value as to whether or not to start the loop, you can toss an if on the front.