Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return outside method error

boolean openingboard;
{   
Robot robot = new Robot();
Color color3 = new Color(108, 25, 85);
Rectangle rectangle = new Rectangle(0, 0, 1365, 770);
    while(true)
    {
    BufferedImage image = robot.createScreenCapture(rectangle);
    search: for(int x = 0; x < rectangle.getWidth(); x++)
        {
        for(int y = 0; y < rectangle.getHeight(); y++)
            {
                if(image.getRGB(x, y) == color3.getRGB())
                {
                    System.out.println("About to finish and return true");
                    return true;
                }
                System.out.println("About to finish and return false");
            }
        }
    }
}

the error is: java:71: return outside method

return true

^

i don't know what this is happening please help!

like image 631
user1179522 Avatar asked Feb 16 '12 02:02

user1179522


2 Answers

From your comment response above, I am going to make the educated guess that you believe that

boolean openingboard;
{
    return true;
}

defines a Java method called openingboard. This isn't the case. Java follows the C paradigm of requiring you to specify your parameters in parentheses, regardless of whether you have any parameters or not. So, the method

boolean openingboard() {
    return true;
}

is a valid Java method (assuming it is inside some class), as is a version of openingboard with much more code between the curly braces.

That said, I'm going to pass along a few friendly pointers on Java style:

  • Java (and indeed most higher-level language) programmers tend to frown on "forever" loops such as while (true), since those loops make it much harder to determine when the loop actually stops.
  • There is no need for the label search in the code, and labels are even more discouraged than forever loops are.

So, I would recommend rewriting your code to look something like

private boolean openingboard() {
    Robot robot = new Robot();
    Color color3 = new Color(108, 25, 85);
    Rectangle rect = new Rectangle(0, 0, 1365, 770);
    BufferedImage image = robot.createScreenCapture(rect);
    for(int x = 0; x < rectangle.getWidth(); x++) {
        for(int y = 0; y < rectangle.getHeight(); y++) {
            if(image.getRGB(x, y) == color3.getRGB())
                return true;
        }
    }

    return false;
}

assuming of course that you prefer a debugger to trace prints.

like image 76
Adam Mihalcin Avatar answered Oct 28 '22 18:10

Adam Mihalcin


Proper methods look like: boolean openingboard ( )

not like boolean openingboard;

The parenthesis are not optional.

The way you have it: openingboard is a field. There is a init block with a Robot and a color and some for loops nested inside of each other. Inside one of the for loops is a return which is not allowed in an init block.

like image 32
emory Avatar answered Oct 28 '22 17:10

emory