I'm working on an ASCII checkers program right now, and I'm trying to figure out how I should be storing my board state. Obviously I'll need a 2d int/short array(for states 'black', 'white', 'empty'), but I don't know how I should declare this so it is accessible from everywhere in the program, like I'll probably need.

In procedural languages I've used in the past, global variables have been easy, but apparently globals in Java is a really bad practice. Also, I'm working under the constraint of one java file, so I don't know if that limits my options. I'm working in NetBeans, and for this assignment, it's supposed to be one .java file.

Right now I'm just using public static int[][] checkersBoard; right before my main method inside my class. I'm pretty sure that's bad practice though

Thanks!

P.s. This is a bonus question, thats why I havn't been taught how to do this :P

有帮助吗?

解决方案

There's a commonly used middle ground in OO languages, which is an instance variable. In fact, this is one of the bread-and-butter features of OO languages that make them so powerful.

You can design your class to simply have a public int[][] board, removing the static modifier from all methods that operate on the game state.

If your class is called CheckerGame, you can instantiate a new CheckerGame() in your main method, and call methods upon it. The following non-sensical example should get you started:

public class CheckerGame {
    public int[][] board;
    public int getBoard(int row, int col){
        return board[row][col];
    }
    public void setBoard(int row, int col, int val){
        board[row][col] = val;
    }

    public CheckerGame(){ board = new int[8][8];

    public static void main(String... argv){
        CheckerGame game = new CheckerGame();
        game.setBoard(1,2,0);
    }

}

You can then add new methods to operate on the instance (for example moveChecker and checkWin), allowing you to reuse and organize functionality.

其他提示

Problems with global variables arise only in larger projects, where it becomes difficult to track down which lines of code touch the global state and in what order.

Since you have just one class, this won't cause trouble because the variable is technically not even global: you can make it private if you want.

With such a small example it is hard to even justify a non-static variable. Basically, your task is too small for you to be able to observe the benefits of OOP.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top