Home > Mobile >  The return of the line int%=2 in java, and the actual behaviour of the statement
The return of the line int%=2 in java, and the actual behaviour of the statement

Time:12-10

my appologies for a rather simple question, but i wanted to ask about the % operator. If we iterate from 0 up untill any big number and have code

        int  ;
        int %= 2;

what exactly does it do? do we set the //int=int%2 ? how would it work with the example of the actual numbers, and what does the line int %= 2; return?

   private void play() {
        // while the board does not have a winner neither is full
        while(!board.hasWinner() && !board.isFull()) {
            //print the state of the game
            update();
            //set field for the current player and the passed mark
            board.setField(players[current].determineMove(board), players[current].getMark());
            //go to the next player
            current  ;
            // current= current % 2
            //
            current %= 2;
        }
        update();
        printResult();
    }

where the current comes from:

  private int current;

    // -- Constructors -----------------------------------------------

    /**
     * Creates a new Game object.
     * @requires s0 and s1 to be non-null
     * @param s0 the first player
     * @param s1 the second player
     */
    public Game(Player s0, Player s1) {
        board = new Board();
        players = new Player[NUMBER_PLAYERS];
        players[0] = s0;
        players[1] = s1;
        current = 0;
    }

CodePudding user response:

Does this answer your question?

int j = 0;
for (int i = 0; i < 10; i  ) {
    j  ;
    j %= 2;
    System.out.print(j   " ");
}

Output:

1 0 1 0 1 0 1 0 1 0

You can achieve it in one line for neater code:

j =   j % 2;
  •  Tags:  
  • java
  • Related