-1

我在 StackOverflow 上查看了其他问题,但我找不到我的问题的解决方案。我在外部初始化了变量,do{并且在内部使用它们,但是当变量达到某个值时,while 方法不会跳出。

这是我所拥有的:

int aiShotHit = 0;
int shotHit = 0;

do{
  showBoard(board);
  bAi.showAi(ai);
  shoot(shoot,ships);
  bAi.aiHit(aiShoot);
  attempts++;

  if(hit(shoot,ships)){
    hint(shoot,ships,aiShips,attempts);
    shotHit++;
    System.out.println("\nShips Left on the Board: " + shotHit);
  }                
  else
    hint(shoot,ships,aiShips,attempts);

  changeboard(shoot,ships,board);


  if(bAi.aiHit(aiShoot,aiShips)){
    hint(shoot,ships,aiShips,attempts);
    aiShotHit++;
  }                
  else
    System.out.print("");

  bAi.changeAi(aiShoot,aiShips,ai);

}while(shotHit !=3 || aiShotHit !=3);

if (shotHit == 3){
  System.out.println("\n\n\nBattleship Java game finished! You Beat the Computer");

} 
System.out.print("You lost! The Ai beat you");
4

1 回答 1

1

你可能开始说,我希望这个循环直到 shotHit 为 3 或直到 aiHShotHit 为 3。那就是

while (!(shotHit == 3 || aiShotHit == 3));

这是“循环,但不是 shotHit 或 aiShotHit 包含值 3”,但它有点难看,所以你想将否定运算符应用于每个子表达式并去掉一些括号。错误是认为您可以移动否定运算符而无需更改任何其他内容

while (shotHit != 3 || aiShotHit != 3);

仅当 shotHit 为 3 且 aiShotHit 为 3 时才退出循环。这不是您想要的。

正确的变换是

while (shotHit != 3 && aiShotHit != 3);

评论中涵盖了很多内容。如何安全地转换这种表达式的指导方针是 De Morgan 的规则,它描述了如何相互转换连词和析取词。遵循这些规则,您可以移动否定运算符并更改括号而不更改表达式的含义:

"not (A or B)" is the same as "(not A) and (not B)"
"not (A and B)" is the same as "(not A) or (not B)"

需要重新组织表达式以使其更具可读性在编程中经常出现,这是您安全执行此操作所需的工具。如果您想了解更多关于德摩根规则的信息,您可能需要阅读此答案

于 2014-05-13T18:11:49.453 回答