gpt4 book ai didi

java - 如何调用同一个类中的方法?

转载 作者:行者123 更新时间:2023-12-02 12:06:04 25 4
gpt4 key购买 nike

我正在为一个类制作一个骰子游戏,但我不知道如何调用掷骰子方法。

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 voidplayerRolls() 内部,我需要调用 rollDice 方法,但我一直很难弄清楚如何做到这一点。我所做的一切都出现了新的错误。该行中的第一行代码显然是错误的,只是我放入其中的最后一个内容。

最佳答案

您可以直接在playerRolls()中调用rollDice()。只是rollDice();。您现在正在做的是尝试从 int 调用该方法,这很奇怪。 私有(private)方法可以在且只能在其自己的类实例内部调用

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

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

关于java - 如何调用同一个类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46904679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com