Jay Jay - 1 month ago 8
Java Question

How does java global variable work?

I am making

Othello
game in java and have problem to switch other player when
enter
pressed. I declared global variable
public static int counter;
which will increment when enter pressed.

Scanner s = new Scanner(System.in);
move = s.nextLine();
// enter to forfeit
if(move.equals("")){
if(counter%2 == 0){
whiteEnterForfeit = turn(board, "White", "W", "B");
printBoard(board);
counter++;
}
if(counter%2 == 1) {
blackEnterForfeit = turn(board, "Black", "B", "W");
printBoard(board);
counter++;
}
}

/* If coordinate is typed like 2,4 I will be recorded at right spot on the board.

else if(!move.equals("")){
StringTokenizer st = new StringTokenizer(move, ",");
rowMove = Integer.parseInt(st.nextToken());
colMove = Integer.parseInt(st.nextToken());
*/


So once I press enter twice in row, it is supposed to print out
Black-White-Black
. However, mine prints out
Black-White-White.....
. What I think about
static
global variable is that any classes or methods can access and modify its value.

I also increment
counter
when each player successfully plays.
Since its code is over 300lines, you can find it on github (https://github.com/misonam03/TIL/blob/master/Java/Othello.java).
Thanks in advance!

Answer

You hava a recursion here, and then your counter never get incremented:

if(counter%2 == 0){
    whiteEnterForfeit = turn(board, "White", "W", "B");
    printBoard(board);
    counter++;
}

If you move the counter++ before the call you get the print right but eventually you will get a StackOverflowError because the way you implemented the recursion.

I think this video series can help you a lot. It's for a C# GO Game, but it's very similar to what you are doing: Roy Osherove - Building a Go Game Engine With TDD and Pair Programming - Part 1