Search code examples
javaclassmethodsintreturn

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!


Solution

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