I'm learning to code java and at the moment I'm trying to make a basic game of "21".
There are two "do while" loops in the code:
- where I want the player to choose whether he wants to draw a new card and
- where I want the player to choose if he wants to play a new game when the last one finished.
However, it doesn't matter if I answer both questions with "Yes" or "No", the loop always breaks and "ends".
Is there something wrong in my logic?
Thanks a lot for the help.
import java.util.Scanner;
public class twentyOneGame {
public static void main(String[] args) {
int computerCard;
int playerCard;
int playerSumCards = 0;
int computerSumCards = 0;
int cardAmount = 0;
String keepPlaying = "Yes";
String keepGoing;
System.out.printf("Enter your name %n");
Scanner input = new Scanner(System.in);
String playerName = input.nextLine();
do {
do {
playerDraw playerdraw = new playerDraw();
playerCard = playerdraw.getPlayerCard();
playerSumCards += playerCard;
computerDraw computerdraw = new computerDraw();
computerCard = computerdraw.getComputerCard();
computerSumCards += computerCard;
cardAmount += 1;
System.out.printf("Your have %s card(s). Your total is %s. %n", cardAmount, playerSumCards);
input = new Scanner(System.in);
System.out.printf("Do you want to draw another card? Yes or No %n");
keepGoing = input.nextLine();
} while (keepGoing == "Yes" && cardAmount < 3);
if (cardAmount == 1) {
System.out.printf("Your total is %s %n", playerSumCards);
System.out.printf("The computers total is %s %n", computerSumCards);
if (playerSumCards > computerSumCards) {
System.out.printf("Good job %s, you won! %n", playerName);
} else {
if (playerSumCards == computerSumCards) {
System.out.printf("It's a draw! %n");
} else {
System.out.printf("Oh no, the computer won! %n");
}
}
} else {
if (cardAmount == 2) {
System.out.printf("Your total is %s %n", playerSumCards);
System.out.printf("The computers total is %s %n", computerSumCards);
if (playerSumCards > computerSumCards) {
System.out.printf("Good job %s, you won! %n", playerName);
} else {
if (playerSumCards == computerSumCards) {
System.out.printf("It's a draw! %n");
} else {
System.out.printf("Oh no, the computer won! %n");
}
}
} else {
if (cardAmount == 3) {
System.out.printf("Your total is %s %n", playerSumCards);
System.out.printf("The computers total is %s %n", computerSumCards);
if (playerSumCards > computerSumCards) {
System.out.printf("Good job %s, you won! %n", playerName);
} else {
if (playerSumCards == computerSumCards) {
System.out.printf("It's a draw! %n");
} else {
System.out.printf("Oh no, the computer won! %n");
}
}
} else {
}
}
}
input = new Scanner(System.in);
System.out.printf("Do you want to keep playing? Yes or No %n");
keepPlaying = input.nextLine();
if (keepPlaying == "Yes") {
playerSumCards = 0;
computerSumCards = 0;
} else {
System.out.printf("Thanks for playing, %s %n", playerName);
break;
}
} while (keepPlaying =="Yes");
}
}