Home Sharing a declared array between two classes - Java
Reply: 0

Sharing a declared array between two classes - Java

user1514
1#
user1514 Published in August 15, 2018, 8:44 pm

In good practice of OOP I am trying to separate some of my methods into two classes (not the main class).

Both classes require this particular 2D array so that the functionality of the program is executed correctly:

private char [][] board = new char[7][8];

I am unsure how to declare this within one class and be able to access it correctly within the following class so that the functionality is executed as intended.

public class DisplayBoard {


public void printBoard(){

for(int i=1; i<board.length; i++){
    for(int j=0; j<board[i].length-1; j++){
        if(board[i][j] != '\0'){
            System.out.print("| " + board[i][j] + " ");
        }
        else{
            System.out.print("|   ");
        }
    }
    System.out.println("|");
}
System.out.println("  1   2   3   4   5   6   7");
     }
   }

My question is how do I write/rewrite the declaration of this array in one class so that it can be accessed in both classes?

The partial code from the other class is as following

public class Board {

    public void placeCounter(char player, int move){
        boolean placed = false;
        for(int i=board.length-1; i>=0; i--) {
            if(!placed) {
                if(board[i][move -1 ] == '\0') {
                    board[i][move -1] = player;
                    placed = true;
                }
            }
         }
    }

}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306134 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO