我正在为我的一个类(class)编写一个“Nim”程序,其中生成随机数量的石头,然后玩家和计算机轮流从堆中移除 1-3 block 石头。移走最后一 block 石头的玩家失败。
但是,无论该方法内部为计算机生成什么代码,它总是返回 0,因此计算机从堆中取出了 0 个石头。
(了解它们是两个单独的文件也可能会有所帮助。)
//code code code...
System.out.println("You take " + playertake + " stones. There are " + rockCount + " left");
int computerTake = 0;
nimMethods.computerTake(computerTake);
rockCount = rockCount - computerTake;
System.out.println("The computer takes " + computerTake + " stones. There are " + rockCount + " left");
这是我的方法文件:
public class nimMethods
{
static int computerTake(int y)
{
y = (int)(Math.random()*((1 - 1) + 3 + 1)); //randomly generating a value between 1-3
return(y);
}
}
我坚信这是一个逻辑错误,并且源于我对方法的缺乏了解。但在我看来,人们似乎并没有问这个问题。
有人可以帮我吗?并解释一下你的答案,我想学习。
谢谢!
最佳答案
你应该这样做:
computerTake = nimMethods.computerTake(computerTake);
您的代码中 computerTake
的值未发生更改,因此它保持初始化时的 0
状态。
不知道为什么你的 computerTake()
方法需要一个参数。
代码如下:
System.out.println("You take " + playertake + " stones. There are " + rockCount + " left");
int computerTake = 0;
computerTake = nimMethods.computerTake();
rockCount = rockCount - computerTake;
System.out.println("The computer takes " + computerTake + " stones. There are " + rockCount + " left");
和
public class nimMethods
{
static int computerTake()
{
int y = (int)(Math.random()*((1 - 1) + 3 + 1)); //randomly generating a value between 1-3
return(y);
}
}
关于java - 如何将变量传递给类,然后返回到使用不同值定义它的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871742/