我是Java编程的新手,我已经查看了所有其他问题,但似乎没有一个问题可以帮助我解决我的困境。看,每当我使用我的程序时,所有的答案都显示出来,而不仅仅是正确的答案。我不知道如何解决这个问题。如果有人有建议,请告诉我。 :)这里没有电脑,只有两个人或你自己。谢谢。我很可能会过度思考这个问题,最终会变得非常简单。哈哈。
import java.util.*;
public class RPS2 {
public static void main(String[] args) {
String p1;
String p2;
String user1 = "User 1";
String user2 = "User 2";
Scanner keyboard = new Scanner(System.in);
System.out.println("Player 1, please enter your choice [P/R/S]");
p1 = keyboard.nextLine();
System.out.println("Player 2, please enter your choice [P/R/S]");
p2 = keyboard.nextLine();
if(user1.equalsIgnoreCase("p") && user2.equalsIgnoreCase("r"));
System.out.println("Paper covers rock, Player 1 wins!");
if(user1.equalsIgnoreCase("R") && user2.equalsIgnoreCase("S"));
System.out.println("Paper covers rock, Player 2 wins!");
if(user1.equalsIgnoreCase("p") && user2.equalsIgnoreCase("s"));
System.out.println("Scissors cuts paper, Player 2 wins!");
if(user1.equalsIgnoreCase("S") && user2.equalsIgnoreCase("P"));
System.out.println("Scissors cuts paper, Player 1 wins!");
if(user1.equalsIgnoreCase("r") && user2.equalsIgnoreCase("s"));
System.out.println("Rock breaks scissors, Player 1 wins!");
if(user1.equalsIgnoreCase("S") && user2.equalsIgnoreCase("R"));
System.out.println("Rock breaks scissors, Player 2 wins!");
if(user1.equalsIgnoreCase("user2"));
System.out.println("Draw");
}
}
答案 0 :(得分:3)
您将答案放在p1
和p2
中,然后比较user1
和user2
。所以你实际上并没有比较用户输入。
正如@andreicovaciu指出的那样,在每个;
之后你需要删除if
。
答案 1 :(得分:2)
在;
条件的每一个结尾处都有一个跟踪if
...
if(user1.equalsIgnoreCase("p") && user2.equalsIgnoreCase("r"));
----------^
这意味着该语句基本上是关闭的(或什么也不做),紧接着的行将被执行,无论
良好做法会建议您始终将if
条件包围在{...}
中,例如......
if(user1.equalsIgnoreCase("p") && user2.equalsIgnoreCase("r")) {
System.out.println("Paper covers rock, Player 1 wins!");
}
我还会使用if-else
语句
if(user1.equalsIgnoreCase("p") && user2.equalsIgnoreCase("r")) {
System.out.println("Paper covers rock, Player 1 wins!");
} else if(user1.equalsIgnoreCase("R") && user2.equalsIgnoreCase("S")) {
System.out.println("Paper covers rock, Player 2 wins!");
} ...
这将进一步降低您在获胜条件下意外获得更多的可能性(但我会以不同的方式构建它,但那只是我;)
您还要比较错误的值(感谢John3136 +1)
String p1;
String p2;
String user1 = "User 1";
String user2 = "User 2";
//...
System.out.println("Player 1, please enter your choice [P/R/S]");
p1 = keyboard.nextLine();
System.out.println("Player 2, please enter your choice [P/R/S]");
p2 = keyboard.nextLine();
if(p1.equalsIgnoreCase("p") && p2.equalsIgnoreCase("r")) {
System.out.println("Paper covers rock, Player 1 wins!");
} else if(p1.equalsIgnoreCase("R") && p2.equalsIgnoreCase("S")) {
System.out.println("Paper covers rock, Player 2 wins!");
} ...
答案 2 :(得分:0)
在每个if
之后你放了一个分号