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;   
}
  • coord are declared in while loop .............if u want to return coord by ur method please declare above the while loop... – hayat Apr 25 '13 at 05:13

2 Answers2

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.
Manish
  • 3,913
  • 2
  • 29
  • 45
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;
    ...
}
Rahul
  • 44,383
  • 11
  • 84
  • 103