import java.util.Scanner;
public class RockPaperScissors
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.println("Player 1: Choose rock, paper or scissors: ");
String Player1 = scan.next().toLowerCase();
System.out.println("Player 2: Choose rock, paper or scissors: ");
String Player2 = scan.next().toLowerCase();
System.out.println ("Player 1 chose " + Player1);
System.out.println ("Player 2 chose " + Player2);
if (Player1.!equals("rock" + "paper" + "scissors")
{
System.out.println ("Please insert either Rock Paper or Scissors!);
}
if (Player1.equals(Player2))
{
System.out.println ("Its a tie!");
}
if ((Player1.equals("rock")) && (Player2.equals("paper")))
{
System.out.println ("Player 2 wins!");
}
else if ((Player1.equals("paper")) && (Player2.equals("rock")))
{
System.out.println ("Player 1 wins!");
}
if ((Player1.equals("scissors")) && (Player2.equals("paper")))
{
System.out.println ("Player 1 wins!");
}
else if ((Player1.equals("paper")) && (Player2.equals("scissors")))
{
System.out.println ("Player 2 wins!");
}
if ((Player1.equals("rock")) && (Player2.equals("scissors")))
{
System.out.println ("Player 1 wins!");
}
else if ((Player1.equals("scissors")) && (Player2.equals("rock")))
{
System.out.println ("Player 2 wins!");
}
}
}
我制作了一个简单的Rock Scissors Paper游戏,但是我想实现验证,因此如果用户输入Rock Paper Scissors以外的任何内容,将会通知用户。我和.!equals
一起去了,但我收到的错误是<identifier>
预期。
谢谢!
答案 0 :(得分:7)
语法错误:
Player1.!equals
更改为:
!Player1.equals
答案 1 :(得分:4)
正确的语法是
if (!Player1.equals("rock" + "paper" + "scissors"))
无论如何,这都不符合您的目的,应该是:
if (!Player1.equals("rock")
&& !Player1.equals("paper")
&& !Player1.equals("scissors"))
或等效的
if (!(Player1.equals("rock")
|| Player1.equals("paper")
|| Player1.equals("scissors")))
+
运算符连接字符串,因此您要将Player1
与"rockpaperscissors"
进行比较
作为旁注,你应该:
player1
而不是Player1
)启动var名称private static final String PAPER = "paper";
作为类属性).equals()
,以避免NullPointerException
(使用PAPER.equals(player1)
)总而言之,您的代码如下所示:
if (!ROCK.equals(player1)
&& !PAPER.equals(player1)
&& !SCISSORS.equals(player1))
答案 2 :(得分:1)
尝试这样:
if (!Player1.equals("rock" + "paper" + "scissors")
{
System.out.println ("Please insert either Rock Paper or Scissors!);
}
答案 3 :(得分:1)
你的代码甚至不会编译你需要这样的东西:
if (!Player1.equals("rock") && !Player1.equals("paper") && !Player1.equals("scissors")) {
System.out.println ("Please insert either Rock Paper or Scissors!);
}
答案 4 :(得分:1)
除了语法之外,测试在逻辑上是错误的。这样:
if (!Player1.equals("rock" + "paper" + "scissors")) {
意味着同样的想法:
if (!Player1.equals("rockpaperscissors")) {
你真正需要的是这样的:
if (!(Player1.equals("rock") ||
Player1.equals("paper") ||
Player1.equals("scissors"))) {
......其余的逻辑也有点破碎。
最后,我应该指出Player1
和Player2
应分别为player1
和player2
。变量名永远不应以大写字母开头。这是一个很大的风格禁忌。