0

When compiled this static method comes up with the error that the int array variable, coord, cannot be found. I declared it within the method and it is of the type int[] and I can't figure out why it won't work. I have a feeling that it has to do with the method being static, but changing it to static was the only way I found to make that method work in the first place.

I feel like this is probably really simple for anybody but me especially when all I could find on this subject were much more complicated coding issues.

In case this helps.. this method is supposed to return the (x,y) coordinates for a move location. Sorry for probably not inputting the code correctly. First time doing this. Thanks in advance for any help

CODE:

public static int[] getMove(String player)
{
    boolean done = false;
    while(!done)
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Input row for " + player);
        int x = in.nextInt() - 1;
        System.out.println("Input column for " + player);
        int y = in.nextInt() - 1;
        int[] coord = {x,y};
        if(getLoc(coord[0], coord[1]).equals("x") || getLoc(coord[0], coord[1]).equals("o") || coord[0] < 0 || coord[0] > ROWS || coord[1] < 0 || coord[1] > COLUMNS)

        {
            System.out.println("Invalid coordinates... please retry");
        }
        else
        {
            done = true;
        }
    } 
    return coord;   
}
1
  • coord are declared in while loop .............if u want to return coord by ur method please declare above the while loop... Commented Apr 25, 2013 at 5:13

2 Answers 2

2

What you are missing is the scope of the variable. A variable declared in parent block is accessible in child blocks, but not the other way around.

public void someMethod()
{
int x=1;

while(x<10)
{
x++; //x is accessible here, as it is defined in parent block.
int j = 0; //This variable is local to while loop and will cause error if used inside method
j++;
}
System.out.println(j);// The outer block does not know about the variable j!!
}

Now in your case,

  • Notice where you have defined coors, and in what all places you are using it.
  • Try to figure where should you define coors variable.
Sign up to request clarification or add additional context in comments.

Comments

1

That is because the array coord is local to the while loop. And therefore its not visible outside its scope. Move the declaration of coord outside the while and it should work.

int[] coord = new int[2];
while(!done){
    ...
    ...
    coord[0] = x;
    coord[1] = y;
    ...
}

1 Comment

Thank you! I knew it would be something simple like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.