你如何从同一个类调用一个方法?

时间:2017-10-24 07:31:49

标签: java bluej

我正在为一个班级制作一个骰子游戏,我不知道如何调用骰子滚动方法。

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

  }

在我的public void playerRolls()中,我需要调用rollDice方法,而且我一直很难搞清楚如何做到这一点。我所做的一切都出现了新的错误。该行中的第一行代码显然是错误的,这是我放在那里的最后一件事。

2 个答案:

答案 0 :(得分:1)

您可以直接在playerRolls()中调用rollDice()。只是rollDice();。你现在正在做的是尝试从一个奇怪的int调用该方法。 私有方法可以在内部调用,也可以在其内部调用

public void playerRolls(){
   rollDice(); //HERE

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

答案 1 :(得分:0)

Roll1.rollDice()你要做的是调用int类的方法rollDice()(我强烈认为它不存在)。

您只需在同一个班级内拨打this.rollDice()或甚至只是rollDice()

this是指向您当时所处对象的指针。