java - Do-while 循环没有结束
问题描述
这是我的战舰游戏代码的一部分。当我沉没所有船只时,循环并没有停止。我从 player 获取 shoot 数组的输入,从 random 函数获取 compshoot 数组的输入。
do {
System.out.println();
showBoard(board);
shoot(shoot);
System.out.println();
if (board[shoot[0]][shoot[1]]==1 || board[shoot[0]][shoot[1]]==2) {
if (board[shoot[0]][shoot[1]]==1){
System.out.println("Oh no, you sunk your own ship :( ");
myShip--;
board[shoot[0]][shoot[1]]=3;
}
else if (board[shoot[0]][shoot[1]]==2) {
System.out.println("Boom! You sunk a ship!");
compShip--;
board[shoot[0]][shoot[1]]=4;
}
}
else if (board[shoot[0]][shoot[1]]==0) {
System.out.println("Sorry, you missed");
board[shoot[0]][shoot[1]] = 5;
}
compShoot(compShoot, shoot);
System.out.println();
System.out.println("Computers turn : ");
System.out.println();
if (board[compShoot[0]][compShoot[1]]==1 || board[compShoot[0]]
[compShoot[1]]==2) {
if (board[compShoot[0]][compShoot[1]]==1){
System.out.println("The Computer sunk one of your ships!");
myShip--;
board[compShoot[0]][compShoot[1]]=3;
}
else if (board[compShoot[0]][compShoot[1]]==2) {
System.out.println("The Computer sunk one of its own
ships");
compShip--;
board[compShoot[0]][compShoot[1]]=4;
}
}
else if (board[compShoot[0]][compShoot[1]]==0) {
System.out.println("Computer missed");
board[compShoot[0]][compShoot[1]] = 5;
}
System.out.println();
System.out.println("Your ships : " + myShip + " | Computer ships : "
+ compShip);
}while (myShip != 0 || compShip != 0);
解决方案
myShip != 0
如果OR ,您当前的条件使您处于循环compShip != 0
中。
myShip
仅当两个AND compShip
都不为 0时,您才需要留在循环中:
do {
} while (myShip != 0 && compShip != 0);
推荐阅读
- redis - redis sentinel 未启动 /etc/redis-sentinel.conf 不可写:权限被拒绝
- c# - Visual Studio -> 发布到本地文件夹(远程 iis)和排队请求
- css - 标题中带有搜索栏的网格布局
- azure - 文件不在 docker workdir azure web 应用程序中
- javascript - 如何在文本区域中设置每行限制,并在超过 java 脚本中的每行限制时将文本换行到下一行
- ios - 自定义 `UITextField` 子类未出现在屏幕上
- qbo3 - qbo3 批量导入忽略了我的电子表格中的一些行
- c# - C#:在 Visual Studio 控制台中制作落块
- python - 为什么我不能在 python 生成器表达式中使用 `else`(来自 if / else)?
- javascript - 基本 typeORM 包装器未连接创建的连接