做循环不结束

时间:2018-09-17 08:45:21

标签: java do-while

这是我的《战舰》游戏代码的一部分。 当我下沉所有船只时,循环不会停止。 我从播放器获取射击数组,从随机函数获取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);

1 个答案:

答案 0 :(得分:0)

如果myShip != 0 compShip != 0,您的当前状况就会使您陷入循环。

仅当myShip AND compShip都不为0时,您才需要保持循环:

do {

} while (myShip != 0 && compShip != 0);