0

I made a boolean[] called rects. Whenever I type in if (rects[j] == true) or for (boolean b : rects), I get an error saying non-static variable rects cannot be referenced from a static context. Could someone help me fix this and explain what this means?

public class Risk extends Applet implements MouseListener
{
    private boolean[] rects;

    public Risk()
    {
        boolean[] rects = new boolean[42];
    }

    public static void main(String[] args)
    {
        if (rects[j] == true) //ERROR
        for (boolean b : rects) //ERROR
            b = false;
    }
}
  • 1
    You need to create an instance of `Risk` class in `main()` method. – KV Prajapati Jun 02 '14 at 08:18
  • You can't use a class-wide variable (requiring an instance of the class) in a static method (that is used without instance of the class) – Laurent S. Jun 02 '14 at 08:19
  • your `bollean[]` is `non-static` and you are using it in `main` method which is `static` . To overcome the error make your boolean array static or use the `boolean[]` array in non-static method – amit bhardwaj Jun 02 '14 at 08:21
  • If this is an applet (and it seems to be), you wouldn't have a `main` method at all. Once you have an appropriate instance method, you check a bookean just by testing it, not using `==`. E.g.: `if (rects[j])` tests to see if `rects[j]` is `true` and branches into the body of the `if` if it is. It's *already* a `boolean`, no need to use `==` to get one. – T.J. Crowder Jun 02 '14 at 08:21

1 Answers1

0

You are accessing the boolean array from within the main method which is static, and hence you either need to create an object inside main for the class Risk and then use that object to access the array or you need to declare the array itself as static, based on your need.

You can read what static means in java in this link.

Community
  • 1
  • 1
anirudh
  • 4,116
  • 2
  • 20
  • 35