在我的程序中,我试图模拟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);
}
答案 0 :(得分:1)
您的外部循环 运行1001次,它似乎没有出现,因为除了仅运行9次的do{}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);
// 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;
}
}
}