Reputation: 95
I programming a blackjack and I want the method play()
to be executed each time the player loses. Such as:
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();
}
This of course doesnt work as I want it to! Any help would be appreciated.
Upvotes: 1
Views: 2960
Reputation: 374
// 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;
}
}
}
Upvotes: 0
Reputation: 418167
Calling a method from itself is called recursion.
You don't want to do recursion for this, but rather a loop or cycle which keeps repeating its body until the player wants to quit.
Something like this:
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.
}
}
Upvotes: 6
Reputation: 29
You need to add more conditions. Like the situation when playerTotalValue is greater than dealerTotalValue and playerTotalValue<21 or vice versa.
Upvotes: 0
Reputation: 5048
It seems like you need to call your function from outside as endless loop like:
while (true){
play();
}
Or any other condition that you can think of.
Upvotes: 1