This question already has answers here:
Can java labels be used appropriately outside of for loops?
(2 answers)
Closed 7 years ago.
Somewhere going through java good articles, I found that such code compiles perfectly.
public int myMethod(){
http://www.google.com
return 1;
}
description says that http: word will be treated as label and //www.google.com as comment
I am not getting how Java Label is useful outside loop?
Under what situation Java Label outside loop should be used?
Here is one benefit of using labels in Java:
block:
{
// some code
if(condition) break block;
// rest of code that won't be executed if condition is true
}
Another usage with nested-loops:
outterLoop: for(int i = 0; i < 10; i++)
{
while(condition)
{
// some code
if(someConditon) break outterLoop; // break the for-loop
if(anotherConditon) break; // break the while-loop
// another code
}
// more code
}
or:
outterLoop: for(int i = 0; i < 10; i++)
{
while(condition)
{
// some code
if(someConditon) continue outterLoop; // go to the next iteration of the for-loop
if(anotherConditon) continue; // go to the next iteration of the while-loop
// another code
}
// more code
}
Just because it compiles does not mean it is useful.....
Labels are often overlooked in Java (who uses labelled break, and continue ...? ). But, just because the label is not used does not mean it is illegal.
Related
This is my first post, so sorry if I post incorrect or incomplete, I will answer every question and I am open for improvements.
My main method has a for-loop with a recursive method in it, the recursive method also has a for-loop (the recursive method basically replaces a lot of nested for-loops). When a specific case is reached, I want to jump out of the recursive method and out of the for-loop in my main. For visualization:
public static void main(..)
for (int i = 0, i < 100 ; i++) {
//do something
recursivemethod(...)
}
//jump here, if case in method is reached
------------------------
recursivemethod (...)
for (int i = 0; i < 10 ; i++) {
//do something
if (case reached) {//jump out of loop in main}
else {recursivemethod(modified)}
}
As I cannot label my for-loop in main and break Label; in my method (to my knowledge), I tried using a boolean, but because of for-loops and/or recursive call, boolean switches back and has not the wanted effect.
There was a similar question where the user later added his solution, but didn't specify it enough for me to understand and how to implement this in my code, the user was last seen years ago, so I cannot ask him. Can someone please help me?
Thanks a lot in advance!
You probably want to return boolean from your recursive method. E. g. true means that recursive call8ng should stop and exit loop
for (int i = 0, i < 100 ; i++) {
//do something
if(recursivemethod(...))
break;
}
Recursive method
boolean recursivemethod (...) {
for (int i = 0; i < 10 ; i++) {
//do something
if (case reached) {return true;}
else {return recursivemethod(modified)}
return false;
}
}
edit: As I was writing this post, I made my code simpler (lost arrays entirely) and got it working. Yet I am still not sure why this specific code won't work, so I'll keep the question.
Hello.
I am writing a small puzzle game in Java (using Eclipse 4.4.2) and stumbled upon a problem inside one of my methods. Basically - it won't complete the method, it just exits the method after the for loop is done without any warnings or errors (I'm not catching exceptions either). I hope I missed something simple..
Details:
I have a method to set the colors of an object and up to 5 other objects that are linked to it through lines. I set up the color of the main object, then find the linked objects through for-loops and in the end change their colors as well. (Double checked the code for Lines, there are simple return methods and nestA and nestB as data - no problem there). lines is an array with a length of 50, nests as its members.
Here's the code:
public void highlightNests(Nest nest) {
//setting the color of the main object (a nest).
Mappers.setColor(nest, nestHighlight);
//resetting the array. Temp solution, had a return method earlier,
//this is part of the debugging.
connectedNests = null;
connectedNests = new Nest[5];
int i = 0;
Gdx.app.log("highlightNests()", "starting the loop");
for (int j=0; j<lines.length; j++) {
if (lines[j].getNestA() == nest) {
connectedNests[i] = lines[j].getNestB();
i++;
}
if (lines[j].getNestB() == nest) {
connectedNests[i] = lines[j].getNestA();
i++;
}
}
//This is where the program exits the method. The following
//lines are not run.
Gdx.app.log("highlightNests()", "entering loop");
for (int l=0; i<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
}
Deleting the middle section makes the end part run, so there are no errors in the last part.
Your second loop is completely wrong, you declare the counter as l and increment another counter i, you should use l<connectedNests.length change it like this:
for (int l=0; l<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
And the program won't finish method and exits before the loop because, it doesn't even enter the loop as it's incorrect.
You have to use l instead of i in condition like,
for (int l=0; l<connectedNests.length; l++)...
//---------^ l not i
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Break from main/outer loop in a double/nested loop?
I have the following situation:
for(int i = 0; i < schiffe.length-1; i++){
if(schiffe[i].schaden){
schlepper.fliege(schiffe[i].x,
schiffe[i].y,
schiffe[i].z);
schlepper.wirdAbgeschleppt = schiffe[i];
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
break;
}
}
}
}
I want to
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
be performed once and then break out of the inner loop and continue with the for(int i... loop. So I used a break in my code. But I am not really sure if this is right. Does the break cause a break for all loops or just for the second loop?
It breaks only the inner loop, and therefore does what you want. To break more than one level, in Java, you can use a "labelled break" like so:
schiffe_loop:
for(int i = 0; i < schiffe.length-1; i++){
some_stuff();
for(int k = 0; k < stationen.length-1; k++){
if (something_really_bad_happened()) {
break schiffe_loop;
}
}
}
But usually you will not need this.
You may consider making a separate method for the inner loop anyway; it's something you can easily give a name to ("find_available_station" or something like that), and will probably need somewhere else.
Also, please be aware that your loops right now will miss the last element of each array. Think carefully about why you are using < instead of <=; it's exactly so that you use every value from 0 up to but not including the specified one.
break will break the innermost loop, in your case 2nd loop.
To make it break the outer loop you can use a labeled break as:
OUTER:for(...) {
for(...) {
break OUTER;
}
}
break only breaks out of the innermost loop.
break will cause break for closest loop only (second loop)
Just the second one. You can use "goto" of course.
Break statement terminates the closest enclosing loop or switch statement in which it appears in many languages but you can try it and be sure 100%.
put the inner two loops in a function and use return to break out of both of them.
If you need more control, you can use a labeled break. More info here. As others have said, break will close the closest loop.
What about using a boolean you call 'found' and use it like this:
while(!found) {
for(...) {
//todo
}
}
I Think You Can Do One More Thing..
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
k = stationen.length + 1 ;
}
}
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