首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在java中返回行int%=2,以及语句的实际行为

在java中返回行int%=2,以及语句的实际行为
EN

Stack Overflow用户
提问于 2021-12-09 23:19:23
回答 1查看 84关注 0票数 -2

我的回答是一个相当简单的问题,但我想问一下%操作符。如果我们从0迭代到任何大的数字,并且有代码

代码语言:javascript
运行
复制
        int++;
        int %= 2;

它到底是做什么的?我们设置//int=int%2了吗?它将如何与实际数字的示例一起工作,以及int %= 2;行返回什么?

代码语言:javascript
运行
复制
   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();
    }

电流从何而来:

代码语言:javascript
运行
复制
  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;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-10 00:13:00

这能回答你的问题吗?

代码语言:javascript
运行
复制
int j = 0;
for (int i = 0; i < 10; i++) {
    j++;
    j %= 2;
    System.out.print(j + " ");
}

输出:

代码语言:javascript
运行
复制
1 0 1 0 1 0 1 0 1 0

对于更整洁的代码,您可以在一行中实现:

代码语言:javascript
运行
复制
j = ++j % 2;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70297949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档