Home > Back-end >  I want to make a record of all the changes of my array - Java
I want to make a record of all the changes of my array - Java

Time:11-22

I want to make a dynamic array that stores a game board (chess) but the board is stored in a 2d array. how can I update an array by increasing the size without deleting the stored data?

String[][] TablaInicial = new String[17][17];
List<List<String>> Prueba = new ArrayList<List<String>>();
 for (i=0; i<17; i  ) {
                for (y=0; y<17; y  ) {
                    Prueba.get(i).get(y).add(TablaInicial[i][y]);
                }
            }

But I get this error: The method add(String) is undefined for the type String

CodePudding user response:

With a helper method, you could create a log of complete board positions:

 String [][] theBoard = new String [17][17]; 
 List<String[][]> history = new ArrayList <> ();
 ... 
 history.add (copyBoard(theBoard));
 ... 
 String [][] somePastBoard = history.get(m); 
 ... 

The helper method creates a new copy of a board:

 public String [][] copyBoard (String [][] board) {
    // precondition: board must not be empty
    String [][] theCopy = new String [board.length][board[0].length];
    for (int row = 0; row < board.length;   row)
        for (int col = 0; col < board[row].length;    col)
            theCopy [row][col] = board [row][col];
    
    return theCopy; 
}

Edit:

One way to print a board is to use Arrays.deepToString (somePastBoard). This will print out on one line, grouping like this: [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]] for a 3 by 5.

If you want neater results, you could create your own print methods, using a pair of nested loops.

Edit:

To print the entire history, iterate through the log using a for loop: (untested)

  public static void printHistory (List<String[][]> log) {
      for (String [][] board : log) {
         System.out.println ("\n-------");
         for (String [] line : board) {
           System.out.println ();
             for (String s : line) {
                System.out.print (s   " ");
             }
         }
      }
  }

CodePudding user response:

you cannot. Updating the array leads to changing the data in it. You may be able to create another 2D Array. But in the case of a chess game a list or arraylist would be more suitable. I suggest saving every change as an array of the 2 indecies of your board and the change that was made. Since we will deal with a numbers, a number for the kind of piece that was moved and another for the move that was made. This would allow you to keep a log.

  • Related