Jump values in loop "for" - java

I have two "for" loops.
for(n=0;n<6;n++){
for(w=n;w<6;w++){
// if w==4 then go to first loop an continue from n=4!!
}
}
How can i jump to n=4 when w takes value 4; Like old Basic command "goto"..
Thanks

How can i jump to n=4 when w takes value 4; Like old Basic command
"goto"
You can use break to "jump" out of the current loop back to the outer loop:
for(n=0;n<6;n++){
// other code
for(w=n;w<6;w++){
// if w==4 then go to first loop an continue from n=4!!
if (w == 4) {
n = 4;
break;
}
}
// other code
}

Related

How do I branch into a specified part of a loop?

int a = 0;
int b = 0;
int c = 0;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 6; i++) {
b = sc.nextInt();
a =+ b;
c =+ (a + 1);
if (c < 20) {
i = 2;
}
}
if I have lines numbered from 0 to 6 inside the loop, the loop would be
so if c is less than 20, it repeats the operation "c=+(a+1);" until it breaks out of the loop by c>=20.
this is a simplified code from my program, mine is GUI. every time I run the code, it freezes.
use c+= instead of c=+. try that, cheers!
and b+= instead ofb=+.
You can tag a loop and do break or continue instructions, but you need design the flow, it is not possible to go into specified line, because java don't use goto instruction. You can only switch the flow inside loops by those instructions.
myloopTag:
for (...; ...; ...) {
// and you can break current loop by:
break;
// or specific (outer) loop by
break myloopTag;
// you can also use 'continue' to go to the start of the loop and increment again
continue;
// or to 'continue' at a label:
continue myloopTag;
}
You're probably very new to the language. Welcome!
If I understand your description of your intent properly, you want your code to exit the loop when c>=20. Based on your description of numbering your lines and the fact that you have the statement:
if(c<20){
i=2;
}
it seems that you think that the iterator i in the for loop is related to the line that will be executed*. This is not the case. The iterator i is a variable that simply holds an integer (just like a, b, and c in your code).
I suggest you take a look at a tutorial on for loops. It might be helpful for you to review other language basics as well, like how control flow works (this may be a better one to start with, actually).
*This guess at your intent is further supported by you counting that there are 6 lines and that your loop goes up to 6.

What does break statement do in java?

Does anyone knows what the group_skip do?
Maybe it is a basic programming, but I've been programming using Java for some years and just found it today.
group_skip: do {
event = stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
break group_skip;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
Thanks!
This is a labelled loop, when break group_skip; statement is executed, it will jump out of the do while loop which is labelled as group_skip
boolean isTrue = true;
outer: for (int i = 0; i < 5; i++) {
while (isTrue) {
System.out.println("Hello");
break outer;
} // end of inner while
System.out.println("Outer loop"); // does not print
} // end of outer loop
System.out.println("Good Bye");
This outputs
Hello
Good Bye
You can get the concept clear here.
There is a labelled for loop called outer and there is inner while loop
When inner for loop is being executed, it encounters break outer; statement
The outer for loop has a System.out.println"Outer loop" statement but that does not get printed.
This is because break outer causes the control to jump out of labelled for loop directly
Now this example for continue statement
outer: for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // this won't print
} // end of outer loop
System.out.println("Good bye");
This prints
Hello
Hello
Hello
Hello
Hello
Good bye
There is a labelled for loop here and an inner for loop
Inner for loop prints Hello and continues to the outer loop.
Because of this, the statements below inner for loop are skipped and outer loop continues to execute.
At the end of outer for loop, Good Bye is printed
Hope this makes everything clear.
group_skip is a label. Labels allow you to break or continue specific loops when you've got them nested.
Here's what Oracle has to say on the subject.
when ever we use simple break statement then we can only transfer control from inner most loop to the outer most (if we have nesting of loops). for exampel
for(int i=0; i < 10; i++){
if(i==5){
break;
}
}
statement x;
will simply transfer the control to statement x. But if you use it inside nested loops then it will work differently.
for(int i=0; i < 10; i++){
for(int j=0; j < 10; j++)
if(i==5){
break;
}
}
statement y;
}
statement x;
in this case it will send the control to statement y. If you want to send the control from innermost loop to either outermost loop or outside the loop then you need such a break statements with labels. Just do it from your self and you will see interesting output.. :)
group_skip is a label used for things like break. (Also goto and jump in other languages)
In java specifically it would be used to break from a code block identified by the label, behaving just like a break statement in a while loop, except breaking from a labeled code block.
Here is some more discussion on the topic

While loops and step

init;
while (test) {
statements;
step;
}
I had a question about the location of the step in the above while loop. Does it matter where the step is written? In other words does it change the any of the values in the while loop if the step is written as the first statement or somewhere in the middle or at the end? If it does can you provide a short example to illustrate that effect.
The placement of the step could definitely influence the body of the loop. Imagine if the code below were accessing an array, the first example could miss the first element in an array.
This outputs 0-9
int x = 0;
while(x < 10){
System.out.println(x);
x++;
}
This outputs 1-10
int x = 0;
while(x < 10){
x++;
System.out.println(x);
}
The step is just another variable. If the statements inside your loop reference it, then yes, it matters. If not, it's position does not matter (as long as it's somewhere in the loop).

How can a "continue" be used to jump back to the beginning of a "do" loop?

Can someone provide a short example of how a "continue" statement can be used to jump back to the beginning of a "do".
Here is an example:
int i = 0;
do{
if(i == 5)
// Won't print 5 but instead go back to the "top" of do
// but first, will execute the while verification
continue;
System.out.println(i);
}while(i++ < 10);
Example on ideone
A continue statement goes to the beginning of the next iteration. You can't go back in the same iteration. See the docs.

iterator for loops with break

let say my code look like below
for(..)
for(..)
for(..){
break; //this will break out from the most inner loop OR all 3 iterated loops?
}
Your example will break out of the innermost loop only. However, using a labeled break statement, you can do this:
outer:
for(..)
for(..)
for(..){
break outer; //this will break out from all three loops
}
This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:
A break statement with no label
attempts to transfer control to the
innermost enclosing switch, while, do,
or for statement of the immediately
enclosing method or initializer block;
this statement, which is called the
break target, then immediately
completes normally.
Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.
class Loop {
public void loopForXx() {
untilXx();
}
private void untilXx() {
for()
for()
for()
if(xx)
return;
}
}
From the most inner loop :)
int i,j,k;
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
for(k = 0; k < 2; k++)
{
printf("%d %d %d\n", i, j, k);
break;
}
Will produce :
0 0 0
0 1 0
1 0 0
1 1 0
You should take a look here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))
boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
for (int j = 0; j < 10 && !exit; j++) {
exit = true;
}
}
this is in my opinion more elegant than a break..
Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).
Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.
This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:
boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {
if (values.get(i).equals(targetValue)) {
targetFound = true;
}
}
if (!targetFound) {
// handle lookup failure
}
Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.
I sometimes use this solution, which I think is more concise and readable:
lookup: {
for(Value value : values) {
if (value.equals(targetValue)) {
break lookup;
}
}
// handle lookup failure here
}
I think breaking (no pun intended) the rule here results in better code.
it will breake from most inner loop,
if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop

Categories