正在扫描输入的字符串

时间:2012-08-03 00:09:55

标签: java

这段代码从不打印我是赢,输,还是打平,我无法弄明白。我知道他的选择和选择都正确,但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! :|");
    }
}   

}

3 个答案:

答案 0 :(得分:2)

==运算符检查两个对象是否完全相同。两个字符串是不同的对象,但具有相同的值(在它们中具有完全相同的字符)。因此,使用.equals()方法比较字符串是否相等,或使用.compareTo()方法测试不相等的比较。在这种情况下,使用.equals()更容易。

所以这是应该如何做的

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

答案 1 :(得分: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! :|");
}

答案 2 :(得分:0)

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