This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The for loop has four parts: 1) Initializer to configure the counter for the loop 2) Comparison to determine when the loop should stop 3) Increment to count the loop's progress 4) Body to perform an action for each time through the loop
Your code is just one loop inside another. Try looking at this code (based on code I saw on the Sun Forums) and see if you understand how it will work. Then run it to see how it does work. Then apply it to your more complex loop.
Pretty dreadful bit of code there, both because of the awkward "if" and the labelled break.
What you are doing is iterating through an array of arrays; for all i in the range arrayOfInts[i] is in itself an array. It will have been declared as arrayOfInts. The first member (No 0) of arrayOfInts is an array, so you can use a for loop with j to iterate through it. If you find the value you are looking for, the labelled break moves control to outside the for loop; in fact I suspect the label "search:" is just before for (int i = 0 etc so the labelled break takes you outside both loops. Break doesn't restart the loops, unlike continue.
I would suggest you can improve the code by changing the middle bit to found = arrayOfInts[i][j] == searchfor; You can dispense with the labelled break by putting a test for found in the continuation. You would end up with this codeNow let's see how many people disagree with me! I'm sure they will [ August 22, 2008: Message edited by: Campbell Ritchie ]
Joined: Jul 09, 2008
The code is actually from the sun tutorials, I'm just learning about labeled break statement. But point taken
Joined: Oct 13, 2005
I ought to have explained more yesterday.
There is an older programming paradigm called structured programming going back to the classic paper by B�hm and Jacopini in 1966 which demonstrates that all programs can be written with a combination of sequence iteration and selection only (an older concept attributed to Alan Turing in the 1930s says the same with sequence recursion and selection). This was followed 2 years later by a paper by Edsger Dijkstra demonstrating that a "goto" statement is regarded as "harmful." Many people, myself included, regard "break" and "continue" as equivalent to "goto"s. And the labelled version is even worse. As I implied in my earlier posting, there are many people who disagree. Structured programming predated object-oriented programming which wasn't introduced until 1967.
It would have been better to call your thread "What does labelled break mean?"-please look at this FAQ.