int i = 0, j = 5;
tp: for (;;) {
i++;
for (;;) {
if(i > --j) {
break tp;
}
}
System.out.println("i =" + i + ", j = " + j); //Unreachable statement, why?
}
I thought the statement is reachable because there is the break statement before, therefore the statement followed by System.out.println can complete normally, since System.out.println is reachable. Where is the mistake?
Because you have two infinite loops. Change
break tp;
To
break;
And that statement is reachable.
Your break statement brings to back to the start of the outer loop (tp label). That's why you can never reach the println statement.
The inner loop is infinite. If there were nothing inside it, it should be clear that the print is unreachable. If you add a break tp inside it it will break the enclosing loop not the inner one, so the statement remains unreachable.
Either use break to break the inner loop or label the inner loop with tp to correct it.
your code is like
L1 : INFINITE LOOP
{
L2 : INFINITE LOOP
{
break to return to L1
}
SOP("SOmething")
}
So whenever the loop L2 breaks, it takes control back to loop L1 and again the loop L2 starts.
This will continue forever and the control will never be able to exit loop L2 and reach SOP statement, thus SOP statement is unreachable.
Related
I am new to Java and preparing for OCA. I was experimenting with break and continue with label. By description in guide book it seemed both when with label, just bring the control to the label. But using test code neither it is throwing error when label for break is as earlier line nor starting the execution from label.
Though I am never going to use break and continue with label. But it important to understand it from exam point of view.
Sample code:
public class B{
public static void main(String[] args){
int i = 0;
label1: for(;i<=10;i++){
System.out.println(i);
if(i==4)
continue label1;
}
System.out.println("out" + i);
i=0;
label2: for(;i<=10;i++){
System.out.println(i);
if(i==4)
break label2;
}
System.out.println("out" + i);
}
}
Result:
java B
0
1
2
3
4
5
6
7
8
9
10
out11
0
1
2
3
4
out4
Why break is not continuing execution from label?
Also including excerpt from the guide book:
excerpt
My understanding from example in Yassir's answer:
label should have a block to follow.
continue brings control at the start of the block and break brings at the end. Thanks
There is a difference between both statements.
Break (JLS §14.15)
A break statement transfers control out of an enclosing statement.
Continue (JLS §14.16)
[...] Control passes to the loop-continuation point of an iteration
statement.
Example
The following are two very simple example, not useful at all in real life, just to demonstrate the actions using different statements.
// This will print "continue" forever.
CONTINUE_LOOP:
while(true) {
System.out.println("continue");
continue CONTINUE_LOOP;
}
// This will only print "break" once and then break out of the loop
BREAK_LOOP:
while(true) {
System.out.println("break");
break BREAK_LOOP;
}
Break needs simple or nested loops. Your example is having single loop so not able to feel effect. Your example can be modified to demonstrate power of break as follows (not using any for, while loop, need if to avoid code unreachable error):
public class B{
public static void main(String[] args){
int i = 0;
label1:
{
label2:
{
i++;
if(i>0)
break label1;
i++;
}
i++;
}
System.out.println("out" + i);
}
}
The code will print out 1 but if you change if condition to i==0 or i<1 then you will get 3 as answer. If you change break statement to break label2 then you will get 2 as answer.
In case of continue you need label to be a loop label.
Hope it helps you in passing OCA exam.
The break with label will cause the program to continue execution AFTER the label whereas the continue with label will cause the program to continue execution FROM the label. This is because break is for "breaking out" of a loop or label where as continue is for "continuing" execution within a loop or label but at the next loop iteration.
The following break with label example uses 3 loops, all nested within each other. Since there’s no way to completely break out of the outer most loop from inside the inner most loop, we can use the label outer1 to accomplish this and specify the label next to the break statement.
outer1:
for(int i=0; i<5; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<2; k++) {
System.out.println("[" + i + "][" + j + "][" + k + "]");
if(j == 3) {
break outer1;
}
}
}
}
Output:
[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0]
Notice how the last line displayed is “[0][3][0]” which is where j == 3 and that’s where we called break outer1; to break out of the outer most loop.
You can also use labels with the continue statement to continue looping from a specific point. Taking the last example and just changing one line to specify continue outer1; instead of break outer1; will cause the loop to continue looping from the outer1 label instead of breaking out of the loop. Note how each time continue outer1 is called, the code continues from the outer loop after incrementing the loop index i by 1.
outer1:
for(int i=0; i<5; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<2; k++) {
System.out.println("[" + i + "][" + j + "][" + k + "]");
if(j == 3) {
continue outer1;
}
}
}
Output:
[0][0][0]
[0][0][1]
[0][1][0]
[0][1][1]
[0][2][0]
[0][2][1]
[0][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[1][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[1][0][1]
[1][1][0]
[1][1][1]
[1][2][0]
[1][2][1]
[1][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[2][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[2][0][1]
[2][1][0]
[2][1][1]
[2][2][0]
[2][2][1]
[2][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[3][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[3][0][1]
[3][1][0]
[3][1][1]
[3][2][0]
[3][2][1]
[3][3][0] <---- CONTINUE WITH LABEL CALLED HERE
[4][0][0] <---- CONTINUES FROM NEXT ITERATION OF OUTER LOOP
[4][0][1]
[4][1][0]
[4][1][1]
[4][2][0]
[4][2][1]
[4][3][0]
Source: Loops in Java – Ultimate Guide
The idea is basic, I want to iterate through a set of bounds.
The way I wanted to do this is by creating a while statement followed by if statements and then increment at the end, and loop.
Try what I like this never makes it to the print statement at the of the while statement, and I can't understand why. (I've tried doing this with a for loop but was unable to figure it out).
Any idea why I can't have an if statement in the while loop?
double a=lend;
double b=lend+resolution;
double root;
System.out.println("Loop starting now.");
while(b<=rend){
if(poly(coefs, a)*poly(coefs,b)<0){
root = findRoot(coefs, a, b, tolerance);
System.out.println(String.format("%.5g%n", root));
}else if(poly(derivcoefs, a)*poly(derivcoefs, b)<0){
root = findRoot(derivcoefs, a, b, tolerance);
System.out.println(String.format("%.5g%n", root));
}else{
continue;
}
a+=resolution;
b+=resolution;
System.out.println("One iteration over, a="+a+", b="+b);
}
Sure, you can have an if statement in a while loop. Your problem is that the continue statement after the final "else" returns control to the beginning of the while loop. So, your three final lines in the While loop -- incrementing a and b and printing "One iteration over"--aren't going to run. Get rid of that final else { continue; } clause.
So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.
What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.
Here is the simplified code:
int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
while(<condition that is false>)
{
System.out.println("phrase1");
a = input.nextInt();
b = input.nextInt();
}
if(<condition that is false>)
{
i = 1;
}
else
{
System.out.println("phrase2");
}
}
Thanks for your help regardless!
EDIT:
For the sake of emphasis...
What happens:
Infinite loop spewing "phrase2".
What I wanted:
After the else is executed, I wanted to be brought into the inner loop again.
Whatever condition you're using in the inner loop, just make sure it's true.
else
{
System.out.println("phrase2");
// SET THIS TO TRUE: <condition that is false>
}
This way, the inner loop will trigger again.
Your control never enters the below if statement
if(<condition that is false>)
{
i = 1;
}
You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug
It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like
boolean needToRetry;
do {
needToRetry = false;
// do whatever
if (somethingWentWrong) {
needToRetry = true;
// set this at any point where you find you will need to go back
}
} while (needToRetry);
The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)
I want to have a for statement that repeats until a given int reaches a certain value.
For example...
for (int variable = 0; variable < other_variable; variable++) {
The problem with this is that the for statement will never end. It will continue to repeat endlessly. What have I done wrong?
This is my code...
boolean itemexist_check = false;
do {
int i2 = m_area.m_items.size();
for (int i = 0; i < i2; i++) {
String s2 = m_area.m_items.get(i).returnName();
System.out.println("Checking...");
if (s2.contains(s)) {
System.out.println("You take the " + s2 + ".");
itemexist_check = true;
player.addItem(m_area.m_items.get(i));
m_area.m_items.remove(i);
}
else {
//do nothing, repeat loop
}
}
}
while (itemexist_check == false);
In this code, m_area.m_items.size() would return 1, so i2 would be 1.
There are several possibilities:
you change variable inside the body of the loop;
you change other_variable inside the body of the loop;
other_variable is set to a large value, in which case the loop might take a long time to terminate;
your code never completes a certain iteration of the loop, for example:
it's getting stuck inside a nested loop as suggested by #Eng.Fouad in the comments, or
it's waiting for a lock, or
it's blocking inside an I/O call that never completes (or takes a long time to complete) etc.
Without knowing the typical value of other_variable and seeing the body of the loop it's anyone's guess.
On a side note,
String s2 = m_area.m_items.get(i).returnName();
is going to cause an exception if invoked in a subsequent or later repetition after
m_area.m_items.remove(i);
is invoked, because every time m_area.m_items.remove(i) is invoked, the list/array loses an item and its size reduces, which is never reflected in the iteration boundary check.
Surely it is the do/while loop that isn't terminating? That for loop cannot possibly run forever.
You should try a
do {
}while(condition is true)
loop. However that said, you have to implement checks assuming that there will be runaway data or conditions resulting in an infinite loop. Just my 2 cents
I saw this keyword for the first time and I was wondering if someone could explain to me what it does.
What is the continue keyword?
How does it work?
When is it used?
continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:
break terminates the loop (jumps to the code below it).
continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next.
This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:
for(int i=0; i < 10; ++i) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This will print out only the odd numbers.
Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.
As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration
Example: This is a code to print the odd numbers from 1 to 10
the compiler will ignore the print code whenever it sees continue moving into the next iteration
for (int i = 0; i < 10; i++) {
if (i%2 == 0) continue;
System.out.println(i+"");
}
As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet will contain odd numbers only 100%... you are wrong!
Continue is a keyword in Java & it is used to skip the current iteration.
Suppose you want to print all odd numbers from 1 to 100
public class Main {
public static void main(String args[]) {
//Program to print all odd numbers from 1 to 100
for(int i=1 ; i<=100 ; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.
Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.
Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '
public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}
}
It will print: aa cc Out of the loop.
If you use break in place of continue(After if.), it will just print aa and out of the loop.
If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
I'm a bit late to the party, but...
It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:
while ((buffer[i++] = readChar()) >= 0)
continue;
In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.
It's a little more obvious than the equivalent:
while (...)
{ }
and definitely better (and safer) coding style than using an empty statement like:
while (...)
;
continue must be inside a loop Otherwise it showsThe error below:
Continue outside the loop