Home java break in Java out of the loop

break in Java out of the loop




All the good time! This code is taken from the book Head First Java. When executed, the code is obtained in the output console as follows: “6 14”. If you take a leaf and a pen and run this code to get the answer: “6 6”. I started to understand what is the cause, and came across the fact that the for loop with a value of outer = 2; It does not start. I changed the subject to break in if at x = x-3 (ie did the same thing that did not break giving executed line x = x + 3), and got the result: “6 6”. The conclusion that due to the multiple output of the loop by the operator break, does not start the cycle. I’m sorry for the stupid question perhaps, if I may I would like to understand the reason for such behavior of the code.

Answer 1, Authority 100%

You seem to confuse them:

  • break completes the cycle entirely
  • continue completes the body of the loop, but continues the cycle itself

Answer 2, Authority 100%

Discard x = x + 0; it still does nothing, only making a mess in your fragile mind.
In such cases, try to look for the problem in stages, step by step.
Normal people do it with
using the debugger … give you the option of a smoker.

int x = 0;
  int y = 30;
  for (int outer = 0; outer & lt; 3; outer ++) {
    System.out.println ( "Cycle 1 runs" + outer + "/" + y);
    for (int inner = 4; inner & gt; 1; inner--) {
      System.out.println ( "Cycle 2 works" + outer + "/" + y);
      y = y - 2;
      System.out.println ( "Subtracting y =" + y);
      System.out.println ( "x == 6 -?" + (X == 6));
      if (x == 6) {
      x = x + 3;
      System.out.println ( "tripped end of the loop 2 ');
    y = y - 2;
    System.out.println ( "tripped end of cycle 1");
  System.out.println (x + "" + y);

– & gt; I hope this helps you to understand how to construct nested loops. Think of your tags in the output to the console that will give you a picture.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions