【问题标题】:How would I pass a variable through to a class, then back out to the class it was defined in with a different value?我如何将一个变量传递给一个类,然后用不同的值返回到它定义的类?
【发布时间】:2019-07-19 04:24:52
【问题描述】:

我正在为我的一个课程编写一个“Nim”程序,其中生成随机数量的石头,然后玩家和计算机轮流从一堆石头中取出 1-3 块石头。移走最后一块石头的玩家输了。

但是,无论该方法内部为计算机生成什么代码,它总是返回 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);
   }
}

我坚信这是一个逻辑错误,并且是由于我缺乏对方法的了解。但人们似乎并没有问我在哪里看这个问题。

有人可以帮帮我吗?并解释你的答案,我想学习。

谢谢!

【问题讨论】:

    标签: java class methods int return


    【解决方案1】:

    你应该这样做:

    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);
       }
    }
    

    【讨论】:

    • 我假设它会将参数作为computerTake 的新值吐出。感谢您的帮助。
    【解决方案2】:

    这是因为Java是按值传递:将方法参数值复制到另一个变量中,然后将复制的对象传递出去,这就是为什么它被称为按值传递。

    因此,您无法在 computerTake 方法之外看到 y 的“更改”值,因为 y 的值已被复制。

    要修复它,您只需将 computerTake 的值替换为您返回的方法结果

    computerTake = nimMethods.computerTake(computerTake);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 1970-01-01
      • 2019-05-02
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多