我编写了一个 21 点程序,我希望每次玩家输掉时都执行方法 play()
。如:
public void play()
{
System.out.println("Your balance: $" + playerBalance + "\nHow much would you like to bet?");
playerBet = keyboard.nextInt();
System.out.println("Your bet: $" + playerBet);
if(playerTotalValue > 21)
{
playerBalance -= playerBet;
System.out.println("You are busted.\nYour balance: $" + playerBalance);
System.out.println("Press enter to continue...");
keyboard.next();
play();
}
else if(dealerTotalValue > 21)
{
playerBalance += playerBet;
System.out.println("The house is busted.\nYour balance: $" + playerBalance);
System.out.println("Press enter to continue...");
keyboard.next();
play();
}
这当然不能像我想要的那样工作!任何帮助将不胜感激。
最佳答案
从自身调用一个方法被称为recursion .
你不想为此做递归,而是一个不断重复其主体直到玩家想要退出的循环或循环。
像这样:
public void play() {
boolean playAgain = true;
while (playAgain) {
// Your game logic here.
// When the game ends, ask the user if he/she wants to play again
// and store the answer in the playAgain variable.
}
}
关于java - 我怎样才能在同一个方法中调用一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28177906/