用布尔值做循环

时间:2018-01-15 22:53:23

标签: java if-statement boolean

有人可以解释为什么我不能打破循环吗?要打破循环,Player1Pass或Player2Pass应为false。还有一种方法可以打破中间的循环,例如,Player1Pass = true;但是让程序在结束循环之前完成整个循环? - 顺便说一下,我知道代码并不完美。我刚刚开始使用Java的经验。 :)

        boolean Player1Pass = true;
        boolean Player2Pass = true;
        do{ 
        String answer;
        Scanner scan = new Scanner (System.in);

        System.out.println(pName1 +" would you like to DRAFT another card or PASS?" );

            answer = scan.nextLine();
            if (answer.equalsIgnoreCase("DRAFT")) {
                clsCard cardFace = new clsCard();
                System.out.println("Your new card is: " + cardFace);
            } else if (answer.equalsIgnoreCase("PASS")) {
                Player1Pass = true;
            }

        System.out.println(pName2 +" would you like to DRAFT another card or PASS?" );

            answer = scan.nextLine();
            if (answer.equalsIgnoreCase("DRAFT")) {
                clsCard cardFace = new clsCard();
                System.out.println("Your new card is: " + cardFace);
            } else if (answer.equalsIgnoreCase("PASS")) {
                Player2Pass = false;
            }


        }while(Player1Pass || Player2Pass);
}
}

2 个答案:

答案 0 :(得分:3)

我相信您需要将||更改为&&

}while(Player1Pass && Player2Pass);

如果其中一个返回false,那么整个语句将为false,它将退出循环。

答案 1 :(得分:0)

Player1Pass永远不会更改真值,因此每次都会执行while,因为条件是OR(如果只有一个成员为真,则所有条件都为真)。

我认为您需要检查一下您的逻辑。也许应该是while (Player1Pass && Player2Pass),你必须在你的代码中更改其中一个或两个的原始真实状态。