gpt4 book ai didi

java - 你能让一个方法==另一个方法吗?

转载 作者:行者123 更新时间:2023-12-01 07:07:36 26 4
gpt4 key购买 nike

我评论了代码不起作用的地方。为什么不呢?我确保 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");
}
}
}

最佳答案

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

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

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

result(calc, comp); // Reuse them here!

当然,这需要您向 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");
}
}
<小时/>

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

关于java - 你能让一个方法==另一个方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com