Search code examples
javabluej

How do you invoke a method from the same class?


I'm making a dice game for a class and I have no idea how to invoke the dice roll method.

public class PigGame{

  public GVdie die1;
  public GVdie die2;
  public int PlayerScore;
  public int ComputerScore;
  public int RoundScore;
  public int winningScore;
  public int Roll1;

  public PigGame(){
    die1 = new GVdie();
    die2 = new GVdie();
    PlayerScore = (0);
    ComputerScore = (0);
    RoundScore = (0);
    winningScore = (100);
    System.out.println("Welcome to the game of Pig");    
  }

  public int getRoundScore (){
    return RoundScore;   
  }

  public int getPlayerScore (){
    return PlayerScore;
  }

  public int getComputerScore(){
    return ComputerScore;
  }

  public boolean playerWon(){
    if (PlayerScore >= 100)
    return true;
    else
    return false;
  }

  public boolean computerWon(){
    if (ComputerScore >= 100)
    return true;
    else
    return false;
  }

  private void rollDice (){
    die1.roll();
    die2.roll();    
    int roll1 = die1.getValue();
    int roll2 = die2.getValue();
    if ((roll1 == 1) || (roll2 == 1))
    RoundScore = 0;
    else
    RoundScore = roll1 + roll2;      

    System.out.println(die1 + "+" + die2 + "=" + (RoundScore));

  }

  public void playerRolls(){
    Roll1.rollDice();

    System.out.print(PlayerScore);
    if(PlayerScore >= 100)
    System.out.println("You have won the game of Pig!");

  }

Inside of my public void playerRolls() I need to invoke the rollDice method, and I've been having a really hard time figuring out how to do that. Everything I've done has come up with a new error. That first line of code in that line is clearly wrong, just the last thing I put in there.


Solution

  • you can call the rollDice() directly in playerRolls(). just rollDice();. What you are doing now is trying to call the method from an int which is weird. A private method can be called inside, and only inside, its own class instance.

    public void playerRolls(){
       rollDice(); //HERE
    
       System.out.print(PlayerScore);
       if(PlayerScore >= 100)
           System.out.println("You have won the game of Pig!");
    }