gpt4 book ai didi

java - 将变量从类方法传递到另一个类

转载 作者:行者123 更新时间:2023-12-01 13:27:40 27 4
gpt4 key购买 nike

我正在尝试为我的文字游戏创建获胜条件。我有两种方法来决定玩家是否建立了获胜或失败的标准。这些方法位于一个类中,而我想在我的 Controller 类中使用它们。变量是 hitTimes 和 nonHits:

1 类:

if(choiceC > 0 || choiceR > 0)
{
Character currentCharacter;
currentCharacter= grid[choiceR][choiceC];
gameBoard[choiceR][choiceC] = currentCharacter;
loseTest(currentCharacter);
winTest(currentCharacter);

}
}
}
}
public int loseTest(Character currentCharacter)
{
int hitTimes = 0;
if(currentCharacter.minePresent == true)
{

hitTimes = 1;
}
return hitTimes;

}
public int winTest(Character currentCharacter)
{
int nonHits = 0;
if(currentCharacter.minePresent == false)
{
nonHits++;
}
return nonHits;
}

2级:

Grid grid = new Grid();
double notMines = grid.notMine;
View view = new View();
result = grid.toString();
view.display(result);
final int ITERATIONS = 13;
final int numGames = 1000;
for (int i=0;i <= numGames; i++)
{
while (hitTimes != 1 || nonHits != notMines )
{

grid.runGame();
result2 = grid.toString();
view.display(result2);
if(nonHits == ITERATIONS)
{
System.out.println("You Win!");
}
if(hitTimes == 1)
{
System.out.println("You Lose!");
}


}
}

最佳答案

您可以创建 boolean 属性 gameWon 和 gameLost,并将它们都设置为错误的初始值。然后,如果满足条件,您当然可以根据情况将其中之一变为 true。在您的类中也创建 getter 方法,以便您可以从另一个类访问它们。

将其放入第二个方法中:

private boolean gameWon = false;
private boolean gameLost = false;

public boolean getGameWon() {
return gameWon;
}

public boolean getGameLost() {
return gameLost;
}

将 if 条件更改为还具有:

if(nonHits == ITERATIONS)
{
gameWon = true;
}
if(hitTimes == 1)
{
gameLost = true;
}

在您的其他类中创建此类并通过 getters 访问您的 gameWon/gameLost 值。

SecondClass sc = new SecondClass();
boolean isGameWon = sc.gameWon();
boolean isGameLost = sc.gameLost();

希望我给了你一个想法..我看不到你的整个代码,所以这只是我对困扰你的事情所做的假设。干杯!

关于java - 将变量从类方法传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21728981/

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