我编写了一个二十一点,我希望每次玩家失败时执行方法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();
}
这当然不能按我的意愿行事!任何帮助将不胜感激。
答案 0 :(得分:6)
从自身调用方法称为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.
}
}
答案 1 :(得分:1)
似乎你需要从外部调用你的函数作为无限循环:
while (true){
play();
}
或者你能想到的任何其他条件。
答案 2 :(得分:0)
您需要添加更多条件。就像playerTotalValue大于dealerTotalValue和playerTotalValue <21的情况一样,反之亦然。
答案 3 :(得分:0)
// Just add while condition in your method
public void play()
int count = 0;
int max-attempt = 5;
while(true) {
try {
// Some Code
// break out of loop, or return, on success
} catch (Exception e) {
// handle exception
if (++count >= max-attempt) throw e;
}
}
}