简体   繁体   中英

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. 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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM