gpt4 book ai didi

java - 为什么我的 while 循环不读取这两个语句?

转载 作者:行者123 更新时间:2023-11-30 05:46:04 26 4
gpt4 key购买 nike

所以,我有这段代码,旨在使用另一个计算机移动类和字符串输入来玩一个简单的石头、剪刀、布游戏。这是一个学校项目,所以我们应该使用 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");

}

}

最佳答案

这是因为您使用了 and or 子句。

使用|| (最常见的称为“or”)如果第一个表达式为真,将计算第一个表达式,然后(在java中)不会计算第二个表达式并进入循环。

另一方面,使用 &&(最常见的是“and”)将计算表达式的两边,如果它们都为 true,则它将进入循环。

在这种情况下,您希望用户和计算机都没有到达“号码”,在这种情况下您应该使用 &&

关于java - 为什么我的 while 循环不读取这两个语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54816107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com