gpt4 book ai didi

java - 为什么循环不会停止迭代?

转载 作者:行者123 更新时间:2023-12-02 06:01:25 25 4
gpt4 key购买 nike

我是一名 Java 初学者,为我的类(class)编写一个 gui tic-tac-toe 程序。 (没有玩家,只是计算机生成的)。

我的程序中的所有内容都按预期运行,除了一件事;看来我对 checkWinner 的方法调用的放置位置不正确,因为 X 和 O 的分配总是完成。为什么循环不会在产生胜利者后立即结束?

它将根据方法调用返回正确的获胜者,但 for 循环将继续迭代并填充其余部分(因此有时看起来 x 和 o 都获胜,或者一个获胜两次)。我快疯了,认为这可能是我的 checkWinner 方法调用和 if 语句的位置。当我设置 winner = true; 时,不应该取消循环吗?我尝试将它放在每个 for 循环之间、内部和外部,但没有成功:(

我已经标记了我认为有问题的区域//这里出了什么问题?//位于代码该部分的右侧。感谢您的任何意见! :)

  public void actionPerformed(ActionEvent e)
{
int total = 0, i = 0;
boolean winner = false;


//stop current game if a winner is found
do{

// Generate random # 0-1 for the labels and assign
// X for a 0 value and O for a 1 value

for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{

//Generate random number
gameboard[row][col] = (int)(Math.random() * 2);

//Assign proper values
if(gameboard[row][col] == 0)
{
labels[i].setText("X");
gameboard[row][col] = 10; //this will help check for the winner
}

else if(gameboard[row][col] == 1)
{
labels[i].setText("O");
gameboard[row][col] = 100; //this will help check for winner
}


/**Send the array a the method to find a winner
The x's are counted as 10s
The 0s are counted as 100s
if any row, column or diag = 30, X wins
if any row, column or diag = 300, Y wins
else it will be a tie
*/

total = checkWinner(gameboard); **//Is this okay here??//**
if(total == 30 || total == 300) //
winner = true; //Shouldn't this cancel the do-while?


i++; //next label

}
}//end for
}while(!winner);//end while



//DISPLAY WINNER
if(total == 30)
JOptionPane.showMessageDialog(null, "X is the Winner!");
else if(total == 300)
JOptionPane.showMessageDialog(null, "0 is the Winner!");
else
JOptionPane.showMessageDialog(null, "It was a tie!");
}

最佳答案

最简单的方法是立即打破所有循环。 (即使有些人不喜欢这样)

outerwhile: while(true){

// Generate random # 0-1 for the labels and assign
// X for a 0 value and O for a 1 value

for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{

total = checkWinner(gameboard);
if(total == 30 || total == 300)
break outerwhile; //leave outer while, implicit canceling all inner fors.


i++; //next label
}
}//end for
}//end while

然而,这不允许“平局”选项,因为如果没有找到获胜者,则基本上会重新开始游戏。为了允许平局,您根本不需要外部 while,并且当找到获胜者时可以立即保留两个 for:

  Boolean winner = false;
outerfor: for (int row = 0; row < gameboard.length; row++) //rows
{
for (int col = 0; col < gameboard[row].length; col++) //columns
{

total = checkWinner(gameboard);
if(total == 30 || total == 300){
winner = true;
break outerfor; //leave outer for, implicit canceling inner for.

}

i++; //next label
}
}//end for

if (winner){
//winner
}else{
//tie.
}

关于java - 为什么循环不会停止迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22646371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com