jayko03
jayko03

Reputation: 2481

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!

Upvotes: 0

Views: 98

Answers (3)

Daisy Li
Daisy Li

Reputation: 54

I would prefer to write the code this way:

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");
    }
    if(counter%2 == 1) {
        blackEnterForfeit = turn(board, "Black", "B", "W");
    }
    printBoard(board);
    counter++;
 }

Upvotes: 0

SamTebbs33
SamTebbs33

Reputation: 5657

You need to use the else keyword instead of the if. This will fix it because currently, the counter is being incremented when it is even, which will make it odd (and so the second if statement runs).

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

Making the second if an else instead will stop both from being run.

Upvotes: 0

Henrique Smoco
Henrique Smoco

Reputation: 71

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

Upvotes: 2

Related Questions