gpt4 book ai didi

java - 石头剪刀布问题——只有一半返回结果

转载 作者:行者123 更新时间:2023-12-02 01:40:23 24 4
gpt4 key购买 nike

我是 Java 新手,任务是使用嵌套 if 语句编写两人石头/剪子布游戏。我的结果只有一半是打印结果

当我使用“else if ("rock".equals(player1) && "paper".equals(player2))”而不是嵌套的 if 语句时,该程序适用于所有组合,但嵌套的 if 是标题。

    Scanner in = new Scanner(System.in);

System.out.print("Player 1, please choose rock, paper, or scissors: ");
String player1 = in.next();
System.out.print("Player 2, please choose rock, paper, or scissors: ");
String player2 = in.next();

player1 = player1.toLowerCase();
player2 = player2.toLowerCase();


if (player1.equals(player2))
{
System.out.println("It's a tie!");
}

else if ("rock".equals(player1))
{
if ("paper".equals(player2))
{
System.out.println("Paper covers rock - Player 2 wins!");
}
}

else if ("rock".equals(player1))
{
if ("scissors".equals(player2))
{
System.out.println("Rock breaks scissors - Player 1 wins!");
}
}

else if ("paper".equals(player1))
{
if ("scissors".equals(player2))
{
System.out.println("Scissors cut paper - Player 2 wins!");
}
}

else if ("paper".equals(player1))
{
if ("rock".equals(player2))
{
System.out.println("Paper covers rock - Player 1 wins!");
}
}

else if ("scissors".equals(player1))
{
if ("paper".equals(player2))
{
System.out.println("Scissors cut paper - Player 1 wins!");
}
}
else if ("scissors".equals(player1))
{
if ("rock".equals(player2))
{
System.out.println("Rock breaks scissors - Player 2 wins!");
}
}

else
{
System.out.println("Invalid input. Please try again using rock, paper, or scissors");
}

in.close();
}

}

我期望每种输入组合都有输出,但剪刀与石头、石头与剪刀、布与石头不会向控制台产生任何输出。

最佳答案

else if ("rock".equals(player1))    
{
if ("paper".equals(player2))
{
System.out.println("Paper covers rock - Player 2 wins!");
}
}
else if ("rock".equals(player1))
{
if ("scissors".equals(player2))
{
System.out.println("Rock breaks scissors - Player 1 wins!");
}
}

请注意,您有同一张支票两次。当第一个为 true 时,只有该 block 将执行,而下一个 else if... 将被跳过。要解决此问题,只需在一个 block 中对player2 进行所有检查即可:

else if ("rock".equals(player1))    
{
if ("paper".equals(player2))
{
System.out.println("Paper covers rock - Player 2 wins!");
}
else if ("scissors".equals(player2))
{
System.out.println("Rock breaks scissors - Player 1 wins!");
}
}

您还应该了解 switch 语句,它可以为问题提供替代解决方案。

关于java - 石头剪刀布问题——只有一半返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526723/

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