Java won't run because there a break statement outside a loop, but I have it inside a loop

21,338

Solution 1

With regards to your first question, the reason that you're getting a compiler error here:

if (x > 35)
{
    g.drawLine (35, 50, 570, 50);
    g.drawLine (35, 50, 250, 0);

    repaint();
    break;  
}

Is that this break statement is not actually in a loop. In Java, you can break out of while, for, do...while, and switch statements, but not if statements. There's not a particularly good reason for this - it's mainly historical - but the compiler does indeed enforce it.

Of the three aforementioned control structures, for, while, and do...while are referred to as loops because they execute code potentially many times. The break statement in this case is a way of saying "please abort execution of the current loop; I don't want to run it any more." Its opposite is continue, which means "please go to the next iteration of this loop."

The reason you can break out of a switch is because Java's switch statement is based on the C programming language's version of switch in which labels are "fall-through." In this context, break means "I have finished executing all of the code I want to execute in this particular label; please get me out of this statement." Interestingly, you can break out of a switch, but you can't continue.

However, you cannot break out of an if statement. There is no high-level reason for this, and in fact the language designers could just as easily have allowed this behavior to mean "stop executing this part of the if statement." I think the reason they opted not to do this is that if statements have a sort of "implicit break" at the end of each handler. For example, if you write

if (condition()) {
    // A
} else {
    // B
}
// C

Then after executing A, the control flow will immediately jump you to C, rather than falling through to the else handler.

If you want to simulate a break out of of the middle of an if statement, you could do something like this:

if (condition()) {
     // code

     if (someOtherCondition()) {
          // more code
     }
}

The idea here is that you run the if statement for some time, then decide using a second if statement whether or not to run the rest of the code in the loop.

Hope this helps!

Solution 2

if (x > 35) {...} is not a loop it is a statement.

for (int x = 0; x <= 35; x++) {...} is a loop.

while( x <= 35 ) {...} is a loop.

do {...} while ( x <= 35 ) is a loop.

Take the repaint() call out it is redundant.

You really need to go and click the CheckMark on the answers that are "Accepted" on your previous questions, people are going to stop answering you if you don't.

Solution 3

Java won't run because there a break statement outside a loop, but I have it inside a loop.

No, you have it inside an if statement, which is not a loop. Even if it worked, break would be useless there, the statement will be executed only once.

Share:
21,338
lonesarah
Author by

lonesarah

Updated on February 25, 2020

Comments

  • lonesarah
    lonesarah over 4 years

    I'm having two weird errors

    New error is when i tell java to draw a string that displays the coordinateness of x and y, It doesn't.

    public void paint (Graphics g)
    {
        super.paint (g);
    
       //System.out.println ("Boolean: " + this.closeDoors);
    
    
        g.drawString("("+x+","+y+")",x,y);
    }
    

    Link to my program if you to compile it. http://hotfile.com/dl/107032853/c81d927/Pigment.java.html

    This is my complete program

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    
    /**
     *
     * @author George Beazer
     */
    public class Pigment extends JApplet 
    {
        boolean closeDoors;
        private int x = 0;
        private int y = 0;
    
    
        public static void main(String [] args)
        {
                Pigment stuff = new Pigment();
        }
        public Pigment()
    
        {
    
            setBackground (Color.blue);
        }
    
        @Override
        public void init()
        {
             setLayout(new FlowLayout());
             addMouseListener(new MyMouseListener());
        }
        @Override
        public void paint (Graphics g)
        {
            super.paint (g);
    
           //System.out.println ("Boolean: " + this.closeDoors);
    
    
            g.drawString("("+x+","+y+")",x,y);
             if (x > 35)
    
                {
                                g.drawLine (35, 50, 570, 50);
                    g.drawLine (35, 50, 250, 0);
                    g.drawLine (250, 0, 570, 50);
                    g.drawRect (50, 50, 500, 350);
                    g.fillRect (100, 75, 80, 80);
                    g.fillRect (400, 75, 80, 80);
                    g.fillRect (240, 200, 125, 200);
    
    
                }
    
            else
                {        
                g.drawLine (35, 50, 570, 50);
                g.drawLine (35, 50, 250, 0);
                g.drawLine (250, 0, 570, 50);
                g.drawLine (180, 120, 100, 120);
                g.drawLine (400, 120, 480, 120);
                g.drawLine (140, 75, 140, 160);
                g.drawLine (450, 75, 450, 160);
                g.drawRect (50, 50, 500, 350);
                g.drawRect (100, 75, 80, 80);
                g.drawRect (400, 75, 80, 80);
                g.drawRect (240, 200, 125, 200);
                g.drawOval (330,280, 20, 20);
                }
    
    
        }
        private class MyMouseListener implements MouseListener
        {
            public void mouseClicked (MouseEvent e)
            {
                x = e.getX();
                y = e.getY();
    
            }
    
            public void mouseEntered (MouseEvent e)
            {
    
    
            }
            public void mouseExited(MouseEvent e){}
            public void mousePressed (MouseEvent e){
    
            }
            public void mouseReleased (MouseEvent e){}
    
        }
    
    }
    
    • biziclop
      biziclop over 13 years
      I might be missing something but I can't see a single loop in your code sample.
    • Amir Raminfar
      Amir Raminfar over 13 years
      Where is you loop? You only have a break which is in an IF statement.
    • Lucas Zamboulis
      Lucas Zamboulis over 13 years
      You should accept correct answers to your previous questions.
    • Admin
      Admin over 13 years
      You really need to go and click the CheckMark on the answers that are "Accepted" on your previous questions, people are going to stop answering you if you don't.
    • Admin
      Admin over 13 years
      Also hotfile.com is a TERRIBLE place to expect people to download code from. It is a pay site and hideous to deal with if you don't have a subscription. Consider something like the Gist feature of github.com in the future.
  • lonesarah
    lonesarah over 13 years
    Then how do stop repain(); from paint over and over again.
  • lonesarah
    lonesarah over 13 years
    I defined the x and y coordinateness as private int x = 0; private int y = 0;.
  • nico
    nico over 13 years
    @user516805: you're calling repaint within paint... could that be the issue?
  • Kamran koupaee
    Kamran koupaee over 13 years
    I din see your message before :)
  • lonesarah
    lonesarah over 13 years
    Yes i understand that, but how do I make the repaint(); run once?>
  • templatetypedef
    templatetypedef over 13 years
    @user516805- I think the issue is that you're calling repaint within paint, which means that every time the window is painted, it will get painted again. Removing that line should fix this problem.
  • lonesarah
    lonesarah over 13 years
    I'm calling repaint withing pain because i painted something, then i change the paint and I want it to show the paint i made changes to.
  • lonesarah
    lonesarah over 13 years
    How do you make the repaint(); method run once.
  • lonesarah
    lonesarah over 13 years
    @user516805: you're calling repaint within paint... could that be the issue? – nico 6 mins ago I'm calling repaint withing pain because i painted something, then i change the paint and I want it to show the paint i made changes to.
  • lonesarah
    lonesarah over 13 years
    I'm calling repaint withing pain because i painted something, then i change the paint and I want it to show the paint i made changes to.
  • Kamran koupaee
    Kamran koupaee over 13 years
    what do you mean for once. is it your program requirement? if yes then you gotta reconsider your design. is it your debugging requirement? then put the breakpoint on IF condition. It will stop on every execution. you can let it execute first time and can debug second time.
  • templatetypedef
    templatetypedef over 13 years
    @user516805- I understand that, but I don't think that's the place to issue the repaint. If you changed something in your program that causes the display to need to be updated, call repaint from that part of the code. The actual implementation of paint will make the changes show up to the panel once the method returns, and so you don't need to indicate to Java that it needs to be updated once more.
  • lonesarah
    lonesarah over 13 years
    Java repaint is in loop, how do i make it run once.
  • Kamran koupaee
    Kamran koupaee over 13 years
    I can't see any loop in your program. perhaps you are calling it from some other class. I don't know. the worst case solution would be in your class, -- private static int counter = 0; .. and then where you are doing the repain(); .. do it this way .. if (counter == 0){repaint(); counter++;} --- but this isn't "right" solution. just put it this way to help you out
  • lonesarah
    lonesarah over 13 years
    I have another g.drawString("("+x+","+y+")",x,y); is somehow hiding it's self in behind of the object i painted. How do i make g.drawString("("+x+","+y+")",x,y); appear in front or move it.
  • Kamran koupaee
    Kamran koupaee over 13 years
    possibly change of its cordinates. could you share your full progra?
  • nico
    nico over 13 years
    @user516805: from the manual entry for repaint: If this component is a lightweight component, this method causes a call to this component's paint method as soon as possible.. So when in paint you call repaint that in turns calls paint and so on and so on...