Search code examples
javafor-loopmultidimensional-arrayundefined-symbol

My Symbol is Lost in the Maze


I am creating a maze game as part of a university assessment. I've intended to loop through the maze board until I find the character '&' and then return the y coordinate of the player (I've done the same method for getting the x position and getting the same error)

The error I am getting:

MazeGame.java:133: error: cannot find symbol  
return i;  
^  
symbol:   variable i  
location: class MazeGame  
1 error  

And, my code,

public static int getCurrentYPosition() {
    for (int i = 0; i < numberOfRows; i++) {
        for (int n = 0; n < board[i].length; n++) {
            if (board[i][n] == '&') {
                break;
            }
        }
    }
    return i;
}

Why can't it find the symbol?


Solution

  • i isn't in scope after the loop. return when you find it, and handle the case where the character isn't found with a sentinel (like -1). And, as written the break would only apply to the inner loop (so if we make i visible by increasing its' scope, for example) you would then return numberOfRows as i increments until then. So, I think you really wanted something like

    public static int getCurrentYPosition() {
        for (int i = 0; i < numberOfRows; i++) {
            for (int n = 0; n < board[i].length; n++) {
                if (board[i][n] == '&') {
                    return i;
                }
            }
        }
        return -1;
    }
    

    Note that you could also write it with a for-each loop like

    for (int i = 0; i < numberOfRows; i++) {
        for (char ch : board[i]) {
            if (ch == '&') {
                return i;
            }
        }
    }
    return -1;