How would I pass a variable through to a class, then back out to the class it was defined in with a different value?

问题: I'm coding a "Nim" program for one of my classes inwhich a random number of rocks is generated, then the player and computer take turns removing 1-3 rocks from the pile. Th...

问题:

I'm coding a "Nim" program for one of my classes inwhich a random number of rocks is generated, then the player and computer take turns removing 1-3 rocks from the pile. The player to remove the last rock loses.

However, no matter what the code generated for the computer inside the method, it would always return 0, and as such say the computer removed 0 rocks from the pile.

(It also may help to know that these are two separate files.)

//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");

Here is my methods file :

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

I have a strong belief that this a logic error, and is coming from my lack of knowledge on methods. But people don't seem to be asking this question where I look.

Could someone give me a hand? And also explain your answer, i'd like to learn.

Thanks!


回答1:

You should do:

computerTake = nimMethods.computerTake(computerTake);

The value of computerTake is not being changed in your code, so it stays 0 as initialized.

Not sure why your computerTake() method takes a parameter though.

That makes the code as follows:

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

and

public class nimMethods
{
   static int computerTake()
   {
      int y =  (int)(Math.random()*((1 - 1) + 3 + 1)); //randomly generating a value between 1-3
      return(y);
   }
}

回答2:

This is because Java is Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.

So you cannot see "changed" value of y oustide your computerTake method because the value of y was copied.

To fix it you can just replace the value of computerTake with your method result which you've returned

computerTake = nimMethods.computerTake(computerTake);
  • 发表于 2019-02-27 02:37
  • 阅读 ( 186 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除