爪哇岩纸剪刀

时间:2014-06-11 21:14:46

标签: java

看了另一个帖子,但是在我输入我的选择之后我无法弄清楚为什么我的程序,即Rock该程序要么给出2个答案,要么根本没有答案。我知道它类似于前一个帖子,但我不明白为什么回复会有所不同。任何帮助将不胜感激。

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {

public static void main(String[] args) {
System.out.println("Do you want to play Rock Paper Sissors?");
System.out.println("Yes or No?");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();             
if (input.equals("Yes")){
    System.out.println("OK pick your weapon!");
    String weapon = scan.nextLine();
    Random rand = new Random();
    rand.nextInt(3);
    if (rand.nextInt(3) == 0){
    //*0=Rock
        if (weapon.equals("Rock")) {
            System.out.println("I choose Rock, so did you... tie.");                    
        }
        else if (weapon.equals("Paper")){
            System.out.println("I choose Rock and you choose Paper...You Win :( !");
        }
        else if (weapon.equals("Scissors")){
            System.out.println("I choose Rock and you choose Paper...You Lose :) !");
        }               
    }
    if (rand.nextInt(3) == 1){
    //*1=Paper
        if (weapon.equals("Rock")) {
            System.out.println("I choose Paper and you choose Rock...You Lose :)  !");                  
        }
        else if (weapon.equals("Paper")){
            System.out.println("I choose Paper, so did you...tie.");
        }
        else if (weapon.equals("Scissors")){
            System.out.println("I choose Paper and you choose Scissors...You Win :(      !");
        }               
    }
    if (rand.nextInt(3) == 2){
        //*2=Scissors
            if (weapon.equals("Rock")) {
                System.out.println("I choose Scissors and you choose Rock...You Win :(    !");                    
            }
            else if (weapon.equals("Paper")){
                System.out.println("I choose Scissors and you choose Paper...You Lose:) !");
            }
            else if (weapon.equals("Scissors")){
                System.out.println("I choose Scissors, so did you...tie.");
            }               
        }
    }
else {
    System.out.println("OK have a nice day.");
}
}

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

你有三个if语句,每个语句都生成自己的随机值,因此所有三个if语句都可以执行。您应该将rand.nextInt(3)的结果保存一次,并在三个连续的if语句中使用它。我会将连续的三个if语句更改为一系列if / else if语句。

您似乎在调用

的地方几乎找到了正确的解决方案
rand.nextInt(3);

在初始if语句之前,只需将结果保存到变量中。