Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817
Moderator: admin
skeptic783
Posts: 1 Joined: Wed Jan 29, 2014 3:18 pm
Contact:
Post
by skeptic783 » Wed Jan 29, 2014 3:20 pm
Hi, newbie here.
I was looking at question #85 on practice test #1:
Code: Select all
class LoopTest{
public static void main(String args[]) {
int counter = 0;
outer:
for (int i = 0; i < 3; i++) {
middle:
for (int j = 0; j < 3; j++) {
inner:
for (int k = 0; k < 3; k++) {
if (k - j > 0) {
break middle;
}
counter++;
}
}
}
System.out.println(counter);
}
}
Why is it that i increments every time
executes? The label
is
after the for loop that would increment i?
Thanks for any insight.
admin
Site Admin
Posts: 10385 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Wed Jan 29, 2014 10:30 pm
break middle causes only the middle loop (i.e. the j loop) to break. The i loop will continue normally and so i will increment after each iteration of i loop.
Javier
Posts: 66 Joined: Mon Feb 20, 2017 12:31 pm
Contact:
Post
by Javier » Tue Oct 24, 2017 10:16 am
Hi!
I don´t see why after break middle is executed counter increments by one.
Is it not exactly the opposite? just when the if statement is not true the flow is going down to the counter++?
Thank you very much!!
Javier
Posts: 66 Joined: Mon Feb 20, 2017 12:31 pm
Contact:
Post
by Javier » Tue Oct 24, 2017 10:22 am
Because I see that counter++ is inside of the inner loop.
Javier
Posts: 66 Joined: Mon Feb 20, 2017 12:31 pm
Contact:
Post
by Javier » Tue Oct 24, 2017 3:40 pm
I mean inside of the scope:
Does it mean is inside of the inner loop? because now I am very confuse
inner:
for (int k = 0; k < 3; k++) {
if (k - j > 0) {
break middle;
}
counter++;
}
admin
Site Admin
Posts: 10385 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Tue Oct 24, 2017 9:51 pm
counter is incremented because the inner loop gets to complete a few iterations. See the output given in the explanation with an extra print statement. Observe the values of i, j, and k.
Javier
Posts: 66 Joined: Mon Feb 20, 2017 12:31 pm
Contact:
Post
by Javier » Wed Oct 25, 2017 9:51 am
What I don´t understand is why counter++ is read only when is "break middle",
It shoudn´t be read aswell in the other cases?
for (int k = 0; k < 3; k++) {
if (k - j > 0) {
break middle;
}
counter++;// why the flow of the code is not going here when the condition of
//the if is false?
}
Thank you
admin
Site Admin
Posts: 10385 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Wed Oct 25, 2017 11:45 am
It IS going there when the condition is false! Try adding an extra print statement and run the code. That will help you understand the flow.
Javier
Posts: 66 Joined: Mon Feb 20, 2017 12:31 pm
Contact:
Post
by Javier » Wed Oct 25, 2017 11:48 am
Sorry, I got it now, I was blocked and I wasn't doing good the inner loop
Users browsing this forum: Google [Bot] and 11 guests