因此,我有这段代码,旨在使用另一台计算机移动类和字符串输入来玩简单的石头,纸张,剪刀游戏。这是一个学校项目,因此我们应该使用while循环,但是由于某种原因,该循环似乎并没有对参数的两面进行评估,并且在计算机得分达到用户输入(即数字)后就完成了循环-用户输入他们想播放的号码)。 (PS:我是Java的超级新手,所以我仍在尝试降低基础知识:))
public class RockPaperScissors {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int playerScore, computerScore; // score
playerScore = 0;
computerScore = 0;
System.out.println("Enter number of points to win:"); // number of rounds
int number = input.nextInt();
boolean PLAYER_VALID = true;
while ((playerScore < number) || (computerScore < number)) {
System.out.println("Choose Rock, Paper or Scissors:");
String playerMove = input.next().toLowerCase();
if (!(playerMove.equals("rock") // ensuring valid user input
|| playerMove.equals("paper")
|| playerMove.equals("scissors")))
{
PLAYER_VALID = false;
}
// computer move
String computerMove = ComputerOpponent.getMove();
// determining win
if (playerMove.equals(computerMove))
{
System.out.println("The computer chose " + playerMove + " so, it's a tie!");
}
else if (playerMove.equals("rock"))
{
if (computerMove.equals("paper"))
{
System.out.println("Computer chose paper, you lose :(");
computerScore += 1;
}
else {
System.out.println("Computer chose scissors, you win :)");
playerScore += 1;
}
}
else if (playerMove.equals("paper"))
{
if (computerMove.equals("scissors"))
{
System.out.println("Computer chose scissors, you lose :(");
computerScore += 1;
}
else {
System.out.println("Computer chose rock, you win :)");
playerScore += 1;
}
}
else if (playerMove.equals("scissors"))
{
if (computerMove.equals("rock"))
{
System.out.println("Computer chose rock, you lose :(");
computerScore += 1;
}
else {
System.out.println("Computer chose paper, you win :)");
playerScore += 1;
}
}
System.out.println("The current score is "
+ "(" + playerScore + "," + computerScore + ")");
} // while - round
if (computerScore == number)
{
System.out.println("Computer wins. Better luck next time!");
}
else if (playerScore == number)
{
System.out.println("Congrats! You win!");
}
else
System.out.println("Something happened....ERROR");
}
}
答案 0 :(得分:1)
这是因为您正在使用and或子句。
使用|| (最常见的称为“或”)将对第一个表达式进行评估,如果它为true,则(在Java中)将不会对第二个表达式进行评估并进入循环。
另一方面,使用&&(最常见的称为“和”)将对表达式的两边求值,并且如果两个都为true,则它将进入循环。
在这种情况下,您希望用户和计算机都没有达到“数字”,在这种情况下,您应该使用&&