[java] Java Error: illegal start of expression

I'm basically refining, completing and trying to compile a test code from a reference book for java beginners. The objective is to create a guessing game wherein the target is located in 3 continuous cells (I'm holding the locations in an array) and the user guesses the cell no. to destroy the target cell by cell.

I checked out half a dozen posts here on the same error, but I couldn't figure out what was going wrong.

This is my error:

test.java:5: error: illegal start of expression
 public int[] locations={1,2,3};
 ^
1 error

and my code is:

public class test{

        public static void main(String[] args){

            test dot=new test();
            public int[] locations={1,2,3};

            dot.setLocationCells(locations);

            String userGuess="2";
            String result = dot.checkYourself(userGuess);
            String testResult="failed";

            if(result.equals("hit")){
                testResult="passed";
            }


          System.out.println(testResult);
        }

public String checkYourself(String stringGuess){
        int guess=Integer.parseInt(stringGuess);
        String result="miss";
        int numOfHits=0;

        for(int cell:locations){
            if(guess==cell){
                result="hit";
                numOfHits++;
                break;
                }
            }

        if(numOfHits==locations.length){
            result="kill";
            }

       System.out.println(result);
       return result;
    }


public void setLocationCells( int[] locations){
        int[] locns;
        locns=locations;
        }

}

This question is related to java compiler-errors

The answer is


public static int [] locations={1,2,3};

public static test dot=new test();

Declare the above variables above the main method and the code compiles fine.

public static void main(String[] args){

Declare

public static int[] locations={1,2,3};

outside of the main method.


Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.