你能用方法==另一种方法吗?

Bri*_*aXD 0 java methods if-statement equals

我评论了代码不起作用的地方.为什么不呢?我要确保calculate()==computerInput()的,但它打印出"这行不通"!这是为什么?

import java.util.Scanner;

class Drank {

    private static String[] userOption = new String[] { "Rock", "Paper", "Scissors" };
    private static String[] computerOption = new String[] { "Rock", "Paper", "Scissors" };

    public static void main(String[] args) {
        System.out.println("Enter: Rock, Paper Or Scissors");
        System.out.println(calculate());
        System.out.println(computerInput());
        result();
    }

    public static int calculate() {
        Scanner input = new Scanner(System.in);
        String userInput = input.nextLine();

        int calculate = 0;
        if (userInput.equals(userOption[0])) {
            calculate = 0;
        } else if (userInput.equals(userOption[1])) {
            calculate = 1;
        } else if (userInput.equals(userOption[2])) {
            calculate = 2;
        }
        return calculate;
    }

    public static int computerInput() {
        int ai = (int) (Math.random() * 3);
        return ai;
    }

    public static void result() {
            if (calculate() == computerInput()) {
            System.out.println("Computer's Pick:" + computerOption[computerInput()]);
        } else {
            // THIS IS WHERE THE PROBLEM
            // IS! It always prints out
            // the'else' even when both
            // are equal?
            System.out.println("This doesnt work"); 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*aux 7

您正在再次调用方法,而不是使用重用它们的返回值.

int calc = calculate();
int comp = computerInput();

System.out.println(calc);
System.out.println(comp);

result(calc, comp); // Reuse them here!
Run Code Online (Sandbox Code Playgroud)

当然,这需要您为方法添加额外的参数result.

public static void result(int calc, int comp) // Add params here
{
    if(calc == comp) // Compare them here!
    {
        System.out.println("Computer's Pick:" + computerOption[computerInput()] );
    } else
    {
        System.out.println("This doesnt work");
    }
}
Run Code Online (Sandbox Code Playgroud)

当您调用方法两次时,将生成两次随机数,并且会询问用户输入两次.