0

这段代码从不打印我是赢还是输,或者是平局,我无法弄清楚。我知道 hischoice 和 whichpick 都设置正确,但 ifs 似乎不起作用。我是在错误地使用字符串还是在比较它们错误?我是 Java 新手,所以我不确定我做错了什么。

import java.util.Scanner;
import java.util.Random;
public class rps {

public static void main(String[] args) {
    int oppchoice;
    String hischoice = "";
    String whichpick;
    String rock = "rock";
    String paper = "paper";
    String scissors = "scissors";
    Scanner mS = new Scanner(System.in);
    Random mR = new Random();

    System.out.print("Type your choice (rock/paper/scissors): ");
    whichpick = mS.nextLine();

    oppchoice = mR.nextInt(3) + 1;
    if (oppchoice == 1) {
        hischoice = rock;
    }
    if (oppchoice == 2) {
        hischoice = paper;
    }
    if (oppchoice == 3) {
        hischoice = scissors;
    }
    System.out.println(hischoice);

    if ((hischoice == rock) && (whichpick == paper)) {
        System.out.println("You win! :)");
    }
    if ((hischoice == paper) && (whichpick == scissors)) {
        System.out.println("You win! :)");
    }
    if ((hischoice == scissors) && (whichpick == rock)) {
        System.out.println("You win! :)");
    }
    if ((hischoice == rock) && (whichpick == scissors)) {
        System.out.println("You lose! :(");
    }
    if ((hischoice == paper) && (whichpick == rock)) {
        System.out.println("You lose! :(");
    }
    if ((hischoice == scissors) && (whichpick == paper)) {
        System.out.println("You lose! :(");
    }
    if ((hischoice == rock) && (whichpick == rock)) {
        System.out.println("It's a tie! :|");
    }
    if ((hischoice == scissors) && (whichpick == scissors)) {
        System.out.println("It's a tie! :|");
    }
    if ((hischoice == paper) && (whichpick == paper)) {
        System.out.println("It's a tie! :|");
    }
}   

}

4

3 回答 3

2

操作员检查两个==对象是否完全相同。两个字符串是不同的对象,但具有相同的值(其中包含完全相同的字符)。因此,使用任.equals()一方法来比较字符串是否相等或使用该.compareTo()方法来测试不相等的比较。在这种情况下,使用.equals().

所以这是应该怎么做的

if ((hischoice.equals(rock)) && (whichpick.equals(rock))) {
        System.out.println("It's a tie! :|");
    }
于 2012-08-03T00:20:28.637 回答
1

其余答案都是正确的,您需要使用 equals 方法来比较两个 String 对象或任何其他对象。

我还建议您将这些 if 语句压缩为 1 从它应该如下所示:

if ((hischoice.equals(rock)) && (whichpick.equals(rock))) {
        System.out.println("It's a tie! :|");
    }
    if ((hischoice.equals(scissors)) && (whichpick.equals(scissors))) {
        System.out.println("It's a tie! :|");
    }
    if((hischoice.equals(paper)) && (whichpick.equals(paper))){
        System.out.println("It's a tie! :|");
    }

到以下:

if (hischoice.equals(whichpick )) {
    System.out.println("It's a tie! :|");
}
于 2012-08-03T01:33:57.223 回答
0

您应该使用 .equals() 进行字符串比较

于 2012-08-03T00:12:26.577 回答