首页 > 解决方案 > 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);

标签: javado-while

解决方案


myShip != 0 如果OR ,您当前的条件使您处于循环compShip != 0中。

myShip 仅当两个AND compShip都不为 0时,您才需要留在循环中:

do {

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

推荐阅读