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 ;
}
}
Related
Simplified, I basically have an if statement like this:
if(A[random]==1)
A[random]=0;
else
continue;
Now I know the 'continue' is for loop statements and this won't work, but I wanted something after the else that if indeed the else(basicaly the condition was false) was activated it repeated the first if(A[random]==1) statement.
You can use a while statement instead:
while (A[random] != 1) {
A[random] = 0;
// generate a new random...
}
You can try below recursion code and see if this resolve's your query
public class Test {
public void continueIf(){
if(A[random]==1)
A[random]=0;
else {
continueIf();
}
}
public static void main(String[] args) {
new Test().continueIf();
}
}
Please note if, if condition is not satisfy then it will lead to stackoverflowerror. That too it depends on the size of JVM memory. check this link for more details on stackoverflow error.
The if/Else statement won't work by itself with looping through an array. I suggest sticking it in either a For loop or a While loop. The loop will search the array and the if/else statement will check the index for the condition provided. I would also get rid of else too. You don't really need that part just the if.
A for loop in the most basic example would look something like this:
for(var i = 0; i < SIZE; i++)
{
if (A[i] == 1)
A[i] = 0;
}
SIZE would be the size of your array
random = ...; // get first random number
while (A[random] != 1) {
random = ...; // get new random number
}
A[random] = 0; // now is 1, switch it to 0
This should work.The other answers have described while and recursion so i am
also adding a do while loop.
do{
//generate the random number
}while(A[random]!=1)//The loop iterates till the condition A[random]!=1 is satisfied
A[random]==0;//changing the bit to 0
Please note that if there is no bit =1 in the array then this solution will fail because you are generating indexes randomly.
So if the array has no element =1 then it keeps on checking the indexes repeatedly and generates infinite loop.
Hope it helps.happy coding!!
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.
I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!
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
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