java做混乱

时间:2014-05-13 18:01:07

标签: java do-while

我在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");

1 个答案:

答案 0 :(得分:1)

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

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

这是"循环而不是shotHit或aiShotHit包含值3"的情况,但它有点难看,所以你想将否定运算符应用于每个子表达式和摆脱一些parens。错误是认为你可以移动否定运算符而不改变任何其他东西来获取

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

只有在aiShotHit为3的同时shotHit为3时才退出循环。不是你想要的。

正确的转变是

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

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

"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)"

需要重新组织一个表达式以使其更具可读性,这在编程中会占用很多,而且这是为了安全地执行它而需要的工具。如果您想了解有关De Morgan规则的更多信息,可以阅读this answer