【问题标题】:Java: Why is my program only running 9 times instead of 1000 (for and while loops)?Java:为什么我的程序只运行 9 次而不是 1000 次(for 和 while 循环)?
【发布时间】:2015-10-28 01:55:31
【问题描述】:

在我的程序中,我试图模拟 1000 场随机井字游戏。游戏只玩了九次,可能是由于内部嵌套的 do-while 循环。我不知道如何解决这个问题,我尝试将内部 do-while 循环更改为 while 循环,将外部 for 循环更改为 while 循环。我知道这可能是一个简单的错误,但我无法确定错误在哪里。下面是我的这两个循环的代码。提前感谢您的帮助。

for (count = 0; count < 1001; count++) {
    int movecount = 0; 
    int row, col;
    int player = 1;
    do {
        //pick a row
        row = r.nextInt(3);
        //pick a col
        col = r.nextInt(3);
        //check if spot is empty
        if (list[row][col]>0) {continue;}
        //if empty, move current player there, add to count
        list[row][col] = player;
        if (CheckRowWin(player, list)) {
            System.out.println("Player " + player + " won");
            break;
        } else {
            System.out.println("Tie Game");
        }
        movecount++;
        //switch player turn
        player = 3 - player;

    } while (movecount < 9);
    }

【问题讨论】:

  • 在某个时候 list 会被填满,你只需 continue 那个内部循环并跳过其他所有内容。

标签: java for-loop while-loop do-while tic-tac-toe


【解决方案1】:

您的外循环 运行了 1001 次,但它似乎没有运行,因为除了 do{}while() 外,您的外循环中没有任何其他内容,它只运行了 9 次并打印出内容。

for (count = 0; count < 1001; count++) {
    int movecount = 0; 
    int row, col;
    int player = 1;
    do {
        //pick a row
        row = r.nextInt(3);
        //pick a col
        col = r.nextInt(3);
        //check if spot is empty
        if (list[row][col]>0) {continue;}
        //if empty, move current player there, add to count
        list[row][col] = player;
        if (CheckRowWin(player, list)) {
            System.out.println("Player " + player + " won");
            break;
        } else {
            System.out.println("Tie Game");
        }
        movecount++;
        //switch player turn
        player = 3 - player;

    } while (movecount < 9);
    // don't forget to reset movecount
    // so that the inner loop will run again
    movecount = 0;
    // clear the "board" for the next game
    // note: using two nested loops is slow and inefficient
    // but it goes along with the theme of learning loops
    for (int r = 0; r < 3; r++) {
        for (int c = 0; c < 3; c++) {
            list[r][c] = 0;
        }
    }
}

【讨论】:

  • 他的外循环不是循环了1001次吗?包括从 0 到 1000。
  • 控制台由于某种原因仍然只返回九个结果。
  • 我注意到了这一点:if (list[row][col]&gt;0) {continue;} 正在跳过,如果没有清除板。您需要清除板以及设置movecount = 0;
  • 我试图通过在movecount = 0; 代码行下方添加row = 0; col = 0; 来清除板。然而,这似乎并没有将游戏迭代 1000 次。
  • 不,您必须清除 list 的每个单元格,而不仅仅是 rowcol 索引。
猜你喜欢
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多