Search code examples
arraysif-statementfor-loopmultidimensional-arraynested-loops

Loop adding letter to a tile


This bit of code is supposed to be adding a letter to a single tile, but the way it's currently written it's adding a letter to several tiles. How do I fix that? Thanks.

public void add(char c) {
        for (int row = 0; row < 4; row++){
            for (int col = 0; col < 4; col++){
                if (tiles[row][col] != null && tiles[row][col].getLetter() == null){
                    tiles[row][col].setLetter(letters.pop());
                    notifyObservers();
                    break;
                }
            }
            }
        }

Solution

  • The break; only exits the inner loop: for (int col = 0; col < 4; col++)
    So it still runs the outter loop: for (int row = 0; row < 4; row++) and therefore re-enters the inner loop again

    Try replacing break; with a return; to exit the add(char c) function completly. Thus preventing any further loop itterations

    public void add(char c) {
        for (int row = 0; row < 4; row++){
            for (int col = 0; col < 4; col++){
                if (tiles[row][col] != null && tiles[row][col].getLetter() == null){
                    tiles[row][col].setLetter(letters.pop());
                    notifyObservers();
                    return;
                }
            }
        }
    }