How to add elements backwards on a 2D Array

Viewed 47
public void drop(){

    int totalTurns = 0;
    while(totalTurns <= 7){
        System.out.println("What column would you like to drop a piece into?: ");
        Scanner scannerBoard = new Scanner(System.in);
        int columnInput = scannerBoard.nextInt();
        if(columnInput <= makeArray[0].length){
            makeArray[rows-1][columnInput-1] = 'x';

        }
        totalTurns = totalTurns + 1;
    }
    return;
}

I'm making a connect 4 project and I'm trying to make a method that adds a "piece" being dropped into the board. The 8th line shows me adding the character 'x', to the last row and column of an integer I input. If I input 3, two times, how would I get the second "piece" to be dropped not on the bottom row, but the row above it?

1 Answers

Any special reason you have to use an array? It probably would be the easiest to use (Array)Lists instead.

For example, create a list of lists instead of the "makeArray" (which is a strange name anyway):

static final int COLUMNS = 7;
List<List<Character>> board = new ArrayList<>();
for (int i = 0; i < COLUMNS; ++) {
   board.add(new ArrayList<Character>());
}

Now you can just "add" the pieces to the end (or "top") of the correct column (don't forget to check the lower limit of the input, too):

if (columnInput >= 1 && columnInput <= board.length) { // or columnInput <= COLUMNS
    board.get(columnInput-1).add('x');
}
Related