This is a class assignment, I am not asking for anyone to DO the assignment for me but rather I have attempted to my best ability before posting on here in hopes of receiving some help on my 4 errors I am receiving and that my deck is not being shuffled for some reason.
My Assignment Directions:
For this assignment, you will create a program that plays a simple game of War. In this game, each player is dealt a card from the full deck. Whoever has the card with the highest value wins. If the cards that are dealt have the same value, then it is a tie and neither player wins. The player that wins the most rounds wins the game. There is no input required from the players (not very interesting!). You should print the cards that each player is
dealt and the result of that round and the final result of the game. You may want to use user input to implement a delay between each round.
My Card Class:
public class Card {
private int cardNum;
final static String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
final static String[] ranks = {"2", "3","4","5","6","7","8", "9","10", "Jack", "Queen", "King", "Ace"};
Card (int theCard) {
setCardNum (theCard);
}
public void setCardNum (int theCard) {
cardNum = (theCard >= 0 && theCard <= 51)? theCard: 0;
}
public int getCardNum() {
return cardNum;
}
public String toString() {
return ranks[cardNum%13] + " of " + suits[cardNum/13];
}
public String getSuit() {
return suits[cardNum/13];
}
public String getRank() {
return ranks[cardNum%13];
}
public int getValue() {
return cardNum%13;
}
}
My Deck Class(where I have a shuffling error):
public class Deck {
private Card[] deck = new Card[52];
private int topCard;
Deck() {
topCard = 0;
for (int i = 0; i < deck.length; i++)
deck[i] = new Card(i);
}
public void shuffle() {
topCard = 0;
for (int i = 0; i < 1000; i++) {
int j = (int)(Math.random()*52);
int k = (int)(Math.random()*52);
Card tmpCard = deck[j];
deck[j] = deck[k];
deck[k] = tmpCard;
}
}
public Card dealCard() {
Card theCard;
if (topCard < deck.length) {
theCard = deck[topCard];
topCard++;
}
else
theCard = null;
return theCard;
}
}
My War Game Main Program:
import java.util.Scanner;
public class WarGame {
public static void main(String[] args) {
Card[][] hands = new Card[2][1];
Deck myDeck = new Deck();
for (int i = 0; i < 53; i++) {
System.out.printf("\n Round %s of The War \n", i);
for (int c = 0; c < 1; c++)
for (int player = 0; player < hands.length; player++)
hands[player][c] = myDeck.dealCard();
for (int player = 0; player < hands.length; player++) {
System.out.printf("Player %d: ", player);
printHand(hands[player]);
int player1;
int player2;
if (player1.getValue() > player2.getValue())
System.out.println("Player One Wins The War");
else if (player2.getValue() > player1.getValue())
System.out.println("Player Two Wins The War");
else
System.out.println("The War Is A Tie");
}
}
}
public static void printHand(Card[] hand) {
for (int card = 0; card < hand.length; card++)
System.out.printf("%s", hand[card].toString());
System.out.println();
}
}
My Errors Are As Follows:
----jGRASP exec: javac -g WarGame.java
WarGame.java:31: error: int cannot be dereferenced
if (player1.getValue() > player2.getValue())
^
WarGame.java:31: error: int cannot be dereferenced
if (player1.getValue() > player2.getValue())
^
WarGame.java:35: error: int cannot be dereferenced
else if (player2.getValue() > player1.getValue())
^
WarGame.java:35: error: int cannot be dereferenced
else if (player2.getValue() > player1.getValue())
^
4 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Thank You So Much for any Help that can be offered.
player1 and player2 refer to the cards each player is given each round
player1 and player2 are ints and not Integers (which is a Java Class). That means they are not object and don't have methods on them. You can compare them directly as "Sam I Am" said.
You can also cast them as Integers :
if( (new Integer(player1)).compareTo(new Integer(player2)) > 0 )
But this is pretty useless since the comparison you are doing do not need any of the integer methods.
So just use :
if (player1 > player2)
You can read this topic to learn more about autoboxing of Integers.
// import needed classes and packages
import java.util.Scanner;
import java.text.NumberFormat;
import java.io.IOException;
import java.util.Locale;
import java.text.DecimalFormat;
public class Program2
{public static void main(String[] args) throws IOException
{
//Declare Variables
//Creates the cards based on their suite
Card heartCard;
Card diamondCard;
Card spadeCard;
Card clubCard;
int countingPlays = 0;
Scanner keyboard = new Scanner(System.in); //Allows Input
//creates the cardPile array called DeckOfCards
CardPile deckOfCards = new CardPile();
//Creates Player1's Card Pile
CardPile player1Pile = new CardPile();
//Creates Player2's Card Pile
CardPile player2Pile = new CardPile();
//Creates the cards to fill the array (1-14 of hearts/diamonds/spades/clubs).
for(int i = 2; i < 15; i++)
{
char heart = '\u0003';
char diamond ='\u0004';
char spade = '\u0005';
char club = '\u0006';
deckOfCards.add(heartCard = new Card(heart, i));
deckOfCards.add(diamondCard = new Card(diamond, i));
deckOfCards.add(spadeCard = new Card(spade, i));
deckOfCards.add(clubCard = new Card(club, i));
}
//prints out the deck of Cards
System.out.println("Deck Of Cards: " + deckOfCards);
//shuffles the cards
deckOfCards.shuffle();
//Prints out the deck of cards after they are shuffled
System.out.println("Deck of Cards after shuffled: " + deckOfCards);
//Checking the size of the Deck
System.out.println("" + deckOfCards.size());
//Takes the deckOfCards and splits them up into 2 piles for Player1 and Player2
for(int i = 0; i < 26; i++)
{
player1Pile.add(deckOfCards.getTopCard());
player2Pile.add(deckOfCards.getTopCard());
}
//Prints out the deck of Cards and then the player 1's pile and player 2's pile
System.out.println("Player 1's Cards: " + player1Pile);
System.out.println("Player 2's Cards: " + player2Pile);
//checking the size of each players Pile
//Prints the header for the game
System.out.println("Lets have a war!!!");
//Testing tricky spot where the getTopCard removes a the topcard
/*
Card removedTopCard = player1Pile.getTopCard();
System.out.println("Getting player1Pile: " + removedTopCard);
player1Pile.add(removedTopCard);
System.out.println("Player1Pile is " + player1Pile);
System.out.println("Player1Pile size is " +player1Pile.size());
*/
//Starts the game of War
try
{ //do while the sizes of the player piles are greater than 0.
do
{
//gets the top cards of each players Pile
Card player1RemovedTopCard = player1Pile.getTopCard();
Card player2RemovedTopCard = player2Pile.getTopCard();
//Compares the 2 cards to test which is bigger. If player 1's card is smaller than player 2 is the winner
if(player1RemovedTopCard.compareTo(player2RemovedTopCard) < player2RemovedTopCard.compareTo(player1RemovedTopCard))
{
System.out.println("Player 1: " + player1RemovedTopCard + " Player 2: " + player2RemovedTopCard);
System.out.println("Player 2 is the Winner");
player2Pile.add(player1RemovedTopCard);
player2Pile.add(player2RemovedTopCard);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has:" + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
//Compares the 2 cards to test which is bigger. If player 2's card is smaller than player 1 is the winner.
else if(player1RemovedTopCard.compareTo(player2RemovedTopCard) > player2RemovedTopCard.compareTo(player1RemovedTopCard))
{
System.out.println("Player 1: " + player1RemovedTopCard + " Player 2: " + player2RemovedTopCard);
System.out.println("Player 1 is the Winner");
player1Pile.add(player1RemovedTopCard);
player1Pile.add(player2RemovedTopCard);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has:" + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
//Else it is a war
else
{
System.out.println("Player 1: " + player1RemovedTopCard + " Player 2: " + player2RemovedTopCard);
System.out.println("WAR!!!!!!!");
//War if the player has only 4 cards left.
if(player1Pile.size() == 1 || player2Pile.size() == 1)
{
Card player1RemovedTopCard2 = player1Pile.getTopCard();
Card player2RemovedTopCard2 = player2Pile.getTopCard();
System.out.println("Player1's 2nd card is: " + player1RemovedTopCard2 + " Player2's 2nd card is: " + player2RemovedTopCard2);
if(player1RemovedTopCard2.compareTo(player2RemovedTopCard2) > player2RemovedTopCard2.compareTo(player1RemovedTopCard2))
{
System.out.println("Player 1 is the winner of the War! ");
player1Pile.add(player1RemovedTopCard);
player1Pile.add(player1RemovedTopCard2);
player1Pile.add(player2RemovedTopCard);
player1Pile.add(player2RemovedTopCard2);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
else if(player1RemovedTopCard2.compareTo(player2RemovedTopCard2) < player2RemovedTopCard2.compareTo(player1RemovedTopCard2))
{
System.out.println("Player 2 is the winner of the War! ");
player2Pile.add(player1RemovedTopCard);
player2Pile.add(player1RemovedTopCard2);
player2Pile.add(player2RemovedTopCard);
player2Pile.add(player2RemovedTopCard2);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
else
{
if(player2Pile.size() == 0)
{
player1Pile.add(player2RemovedTopCard2);
player1Pile.add(player2RemovedTopCard);
player1Pile.add(player1RemovedTopCard2);
player1Pile.add(player1RemovedTopCard);
}
else
{
player2Pile.add(player2RemovedTopCard2);
player2Pile.add(player2RemovedTopCard);
player2Pile.add(player1RemovedTopCard2);
player2Pile.add(player1RemovedTopCard);
}
}
}
//War if the player has only 2 cards left.
else if(player1Pile.size() == 2 || player2Pile.size() == 2)
{
Card player1RemovedTopCard2 = player1Pile.getTopCard();
Card player1RemovedTopCard3 = player1Pile.getTopCard();
Card player2RemovedTopCard2 = player2Pile.getTopCard();
Card player2RemovedTopCard3 = player2Pile.getTopCard();
do
{
System.out.println("Player1's 3rd card is: " + player1RemovedTopCard3 + " Player2's 3rd card is: " + player2RemovedTopCard3);
if(player1RemovedTopCard3.compareTo(player2RemovedTopCard3) > player2RemovedTopCard3.compareTo(player1RemovedTopCard3))
{
System.out.println("Player 1 is the winner of the War! ");
player1Pile.add(player1RemovedTopCard);
player1Pile.add(player1RemovedTopCard2);
player1Pile.add(player1RemovedTopCard3);
player1Pile.add(player2RemovedTopCard);
player1Pile.add(player2RemovedTopCard2);
player1Pile.add(player2RemovedTopCard3);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
else if(player1RemovedTopCard3.compareTo(player2RemovedTopCard3) < player2RemovedTopCard3.compareTo(player1RemovedTopCard3))
{
System.out.println("Player 2 is the winner of the War! ");
player2Pile.add(player1RemovedTopCard);
player2Pile.add(player1RemovedTopCard2);
player2Pile.add(player1RemovedTopCard3);
player2Pile.add(player2RemovedTopCard);
player2Pile.add(player2RemovedTopCard2);
player2Pile.add(player2RemovedTopCard3);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
//Continues the war if the top card at the end of the war are still equal
}while(player1RemovedTopCard3.compareTo(player2RemovedTopCard3) == player2RemovedTopCard3.compareTo(player1RemovedTopCard3));
}
//War if the player has only 3 cards left.
else if(player1Pile.size() == 3 || player2Pile.size() == 3)
{
Card player1RemovedTopCard2 = player1Pile.getTopCard();
Card player1RemovedTopCard3 = player1Pile.getTopCard();
Card player1RemovedTopCard4 = player1Pile.getTopCard();
Card player2RemovedTopCard2 = player2Pile.getTopCard();
Card player2RemovedTopCard3 = player2Pile.getTopCard();
Card player2RemovedTopCard4 = player2Pile.getTopCard();
do
{
System.out.println("Player1's fourth card is: " + player1RemovedTopCard4 + " Player2's fourth card is: " + player2RemovedTopCard4);
if(player1RemovedTopCard4.compareTo(player2RemovedTopCard4) > player2RemovedTopCard4.compareTo(player1RemovedTopCard4))
{
System.out.println("Player 1 is the winner of the War! ");
player1Pile.add(player1RemovedTopCard);
player1Pile.add(player1RemovedTopCard2);
player1Pile.add(player1RemovedTopCard3);
player1Pile.add(player1RemovedTopCard4);
player1Pile.add(player2RemovedTopCard);
player1Pile.add(player2RemovedTopCard2);
player1Pile.add(player2RemovedTopCard3);
player1Pile.add(player2RemovedTopCard4);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
else if(player1RemovedTopCard4.compareTo(player2RemovedTopCard4) < player2RemovedTopCard4.compareTo(player1RemovedTopCard4))
{
System.out.println("Player 2 is the winner of the War! ");
player2Pile.add(player1RemovedTopCard);
player2Pile.add(player1RemovedTopCard2);
player2Pile.add(player1RemovedTopCard3);
player2Pile.add(player1RemovedTopCard4);
player2Pile.add(player2RemovedTopCard);
player2Pile.add(player2RemovedTopCard2);
player2Pile.add(player2RemovedTopCard3);
player2Pile.add(player2RemovedTopCard4);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
//Continues the war if the top card at the end of the war are still equal
}while(player1RemovedTopCard4.compareTo(player2RemovedTopCard4) == player2RemovedTopCard4.compareTo(player1RemovedTopCard4));
}
//war if player has more than 4 cards
else if(player1Pile.size() >= 4 || player2Pile.size() >= 4)
{
Card player1RemovedTopCard2 = player1Pile.getTopCard();
Card player1RemovedTopCard3 = player1Pile.getTopCard();
Card player1RemovedTopCard4 = player1Pile.getTopCard();
Card player1RemovedTopCard5 = player1Pile.getTopCard();
Card player2RemovedTopCard2 = player2Pile.getTopCard();
Card player2RemovedTopCard3 = player2Pile.getTopCard();
Card player2RemovedTopCard4 = player2Pile.getTopCard();
Card player2RemovedTopCard5 = player2Pile.getTopCard();
do
{
System.out.println("Player1's 5th card is: " + player1RemovedTopCard5 + " Player2's 5th card is: " + player2RemovedTopCard5);
if(player1RemovedTopCard5.compareTo(player2RemovedTopCard5) > player2RemovedTopCard5.compareTo(player1RemovedTopCard5))
{
System.out.println("Player 1 is the winner of the War! ");
player1Pile.add(player1RemovedTopCard);
player1Pile.add(player1RemovedTopCard2);
player1Pile.add(player1RemovedTopCard3);
player1Pile.add(player1RemovedTopCard4);
player1Pile.add(player1RemovedTopCard5);
player1Pile.add(player2RemovedTopCard);
player1Pile.add(player2RemovedTopCard2);
player1Pile.add(player2RemovedTopCard3);
player1Pile.add(player2RemovedTopCard4);
player1Pile.add(player2RemovedTopCard5);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
else if(player1RemovedTopCard5.compareTo(player2RemovedTopCard5) < player2RemovedTopCard5.compareTo(player1RemovedTopCard5))
{
System.out.println("Player 2 is the winner of the War! ");
player2Pile.add(player1RemovedTopCard);
player2Pile.add(player1RemovedTopCard2);
player2Pile.add(player1RemovedTopCard3);
player2Pile.add(player1RemovedTopCard4);
player2Pile.add(player1RemovedTopCard5);
player2Pile.add(player2RemovedTopCard);
player2Pile.add(player2RemovedTopCard2);
player2Pile.add(player2RemovedTopCard3);
player2Pile.add(player2RemovedTopCard4);
player2Pile.add(player1RemovedTopCard5);
System.out.println("Player 1 has: " + player1Pile.size() + " cards left.");
System.out.println("Player 2 has: " + player2Pile.size() + " cards left.");
System.out.println("\n");
keyboard.nextLine();
}
//Continues the war if the top card at the end of the war are still equal
}while(player1RemovedTopCard5.compareTo(player2RemovedTopCard5) == player2RemovedTopCard5.compareTo(player1RemovedTopCard5));
}
}
//Adds to the plays that keep track of how many plays have been made
countingPlays++;
//. If there are 10 plays it shuffles and prints out a message that the cards have been shuffled.
if(countingPlays >= 10)
{
player1Pile.shuffle();
player2Pile.shuffle();
System.out.println("Cards Shuffled");
//resets the counter to 0
countingPlays = 0;
}
//Continues the game of war while the players piles are bigger than 0
}while(player1Pile.size() > 0 || player2Pile.size() > 0);
}
//Catches the Array 0 error and prints out who is the winner based on who has zero cards.
catch (IndexOutOfBoundsException theException) //tries to catch this type...
{
if(player1Pile.size() == 0)
{
System.out.println("Winner is Player 2" );
}
else
System.out.println("Winner is Player 1" );
}
} //end of main
}//end of class
I'm half guessing, but I don't think you need to call getValue() on your ints
a statement like
if (player1 > player2)
is perfectly fine, assuming that both player1 and player2 are ints
You need to get the value of the Card objects in hands. You currently aren't actually assigning anything to player1 and player2. To get the value of the cards you need to call .getValue() on the actual objects, like int player1 = hands[0][0].getValue();
I updated your main function to demonstrate how it should look, and also made a few other changes that might help you later on.
public static void main(String[] args) {
Card[][] hands = new Card[2][1];
Deck myDeck = new Deck();
//reduced this to 26 iterations because two cards are dealt each iteration
for (int i = 0; i < 26; i++) {
System.out.printf("\n Round %s of The War \n", i);
//You really don't need to loop just once here...
//Simply assign the card to hands[player][0] since that's the only option
//for (int c = 0; c < 1; c++)
for (int player = 0; player < hands.length; player++)
hands[player][0] = myDeck.dealCard();
for (int player = 0; player < hands.length; player++) {
System.out.printf("Player %d: ", player);
printHand(hands[player]);
}
int player1 = hands[0][0].getValue(); //get the value from the Card object
int player2 = hands[1][0].getValue();
if (player1 > player2)
System.out.println("Player One Wins The War");
else if (player2 > player1)
System.out.println("Player Two Wins The War");
else
System.out.println("The War Is A Tie");
}
}
For the shuffle method you could use this code:
public void shuffle()
{
Collections.shuffle(deck);
}
Related
I am coding a pig game in Java, and I need help adding up the score. The game's goal is to roll two dice, and the values of those two dice are added together, and the player who gets to 100 first wins. I want to loop the values (which I called "Added") so that it continuously adds up by themselves.
Thank you in advance
By the way, I'm hardly done most of the game, so mind the gaps, lol.
import java.util.Random;
import java.util.Scanner;
public class Pig {
static int player, Continue, roll1, roll2;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
Random r2 = new Random();
System.out.print("Enter 1 to play against computer\nEnter 2 to play against another person\n");
player = keyboard.nextInt();
if (player == 1) {
System.out.println("\nPlaying against the computer...");
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added = roll1 + roll2;
System.out.println("\nYour total is " + added);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
if (Continue == 1) {
do {
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added2 = roll1 + roll2;
int added3 = added + added2;
added = added2;
added2 = added3;
System.out.println("\nYour total is " + added3);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
} while (Continue == 1);
}
} else {
System.out.print("Bye");
}
/*if (player == 2){
System.out.println("Playing against another person...");
}
else {
System.out.print("Bye");
count++;
*/
}
}
I am building a war card game for an assignment I have the game built and it is working but I am running into the issue such as card 10 jack of spades is less in value as say card 23 the jack of hearts. Looking for advice about the best way to be able to compare the cards to see if they are equal.
Below is the code I have so far:
import java.util.Random;
import java.util.Scanner;
public class WarGame {
public static void main(String a[]) {
DeckOfCards d = new DeckOfCards();
int input = 0;
int computer = 0;
int you = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
while (input != 2) {
if (input == 1) {
System.out.print("\n\nEnter the value of the card:");
int card = sc.nextInt();
if (card >= 0 && card <= 51) {
int systemCard = d.computerTurn(card);
System.out.println("Your card - " + d.inputCard(card));
System.out.println("Computer card - " + d.inputCard(systemCard));
if(systemCard > card)
++computer;
else
++you;
System.out.println("The winner is " + (systemCard > card ? "Computer" : "You"));
} else {
System.out.println("Invalid card");
}
}
else {
System.out.println("That is an invalid selection please choose 1 or 2.");
}
System.out.print("\n1.To play\n2.Exit\nEnter the choice:");
input = sc.nextInt();
}
System.out.println("Total Wins by Computer: "+ computer);
System.out.println("Total Wins by You: "+ you);
if (computer > you)
System.out.println("Computer is the champion");
else if (computer == you)
System.out.println("Its a Tie");
else
System.out.println("You are the champion");
}
}
class DeckOfCards {
String suits[] = {"Spades", "Hearts", "Diamonds", "Clubs"};
Random ran = new Random();
int systemWin = 0;
int playerWin = 0;
String inputCard(int card) {
int suit = card / 13; //assigning suit to your card
int rank = card % 13; //Assigning rank to your card
String out = "";
switch (rank) { //Setting up face cards for the cases
case 0:
out = "Ace of " + suits[suit];
break;
case 10:
out = "Jack of " + suits[suit];
break;
case 11:
out = "Queen of " + suits[suit];
break;
case 12:
out = "King of " + suits[suit];
break;
default:
out = rank + 1 + " of " + suits[suit]; //Adding one to remainder so it will go from 2-10 instead of 1-9
break;
}
return out;
}
int computerTurn(int playerRank) { //Keeping track of the wins for computer and player
int systemRank = this.ran.nextInt(51);
if (systemRank > playerRank)
systemWin++;
else
playerWin++;
return systemRank;
}
}
I think you're comparing the index to your deck rather than the card values themselves. If I'm understanding, you want to compare d.inputCard(card) with d.inputCard(systemCard) instead of card with systemCard. But of course, that's a String. Having a hard time following the code :-).
I've almost got this thing working, I just can't manage to get the:
if((pscore <= card1 +card2)) statement to loop until the player either sticks or busts.
from what I can see, it should work... but I'm missing a detail, and I can't figure out what.
import java.util.Random;
import java.util.Scanner;
class Blackjack
{
public static void main(String[] args)
{
Random r = new Random();
String name;
Scanner scannerIn = new Scanner(System.in);
boolean yourTurn = true;
boolean dealersTurn =true;
int card1 = 1 + r.nextInt(11);
int card2 = 1 + r.nextInt(11);
int dcard1 = 1 + r.nextInt(11);
int dcard2 = 1 + r.nextInt(11);
int pscore = card1 +card2;
int dscore = dcard1 +dcard2;
System.out.println("Welcome to Blackjack ! " );
System.out.println("\nScore as close to 21 without going over to win ");
System.out.println("\nWhat is your name?");
name = scannerIn.nextLine();
System.out.println("\nHello " + name);
System.out.println("\nLet's play some BlackJack!");
System.out.println("\nThe dealer shows:\t" +dcard1 );
System.out.println("\n\nYour first card is:\t " +card1 );
System.out.println("\nYour second card is:\t" +card2 );
System.out.println("\nGiving you a grand total of: " +pscore );
while (yourTurn)
{
if ((pscore <= +card1 +card2))
System.out.println("\nWould you like to (H)it or (S)tick?");
String a = scannerIn.nextLine();
if(a.toLowerCase().equals("h"))
{
int newCard = 1 + r.nextInt(11);
System.out.println("\nYour next card is " +newCard );
pscore = pscore +newCard;
System.out.println("\nGiving you a new total of "+pscore);
if ((pscore >=22))
{
System.out.println("\nYou Busted! \nSorry! you lose");
yourTurn = false;break;
}
}
else if(a.toLowerCase().equals("s"))
{
yourTurn = false;
System.out.println("\nYou stick at " +pscore );
System.out.println("\nNow it's the dealers turn\n Dealer must draw until 17");
}
else
{
System.out.println("\nPlease press H or S");
}
while (dealersTurn)
{
dealersTurn = true;
{ if ((dscore <= dcard1+dcard2))
System.out.println("\nThe dealers cards were:\n " +dcard1);
System.out.println("\nand\n" +dcard2);
System.out.println("\nGiving the Dealer a grand total of: " +dscore );
}
{
int newCard1 = 1 + r.nextInt(11);
if ((dscore<=17))
System.out.println("\nThe dealer draws a: " +newCard1 );
dscore = dscore +newCard1;
System.out.println("\nGiving the dealer a grand total of: "+dscore);
}
if ((dscore >=22))
{
System.out.println("\nDealer Bust!");
System.out.println("\nThe House loses");
System.out.println("\nYou Win");
dealersTurn = false;break;
}
else if ((dscore >=pscore))
{
System.out.println("\nDealer has " +dscore);
System.out.println("\nThe dealer beat you!");
System.out.println("\nThe House Wins!");
dealersTurn = false;break;
}
}
}
scannerIn.close();
}
}
Also, I have a bunch of people to thank, helping me get this far. If there is a +1 button for people I can't find it.
Thanks for the help
Vincent.
Your while(yourTurn) loop does not close its bracket until after the while(dealerTurn) loop. This is causing the dealers turn to be a part of the yourTurn loop. Add a closing bracket above the dealersTurn while loop as follows:
}
while (dealersTurn)
{
Then remove the old closing bracket from the bottom above "scannerIn.close()"
But also, what is the purpose of your logic
if ((pscore <= +card1 +card2))
Your score is = to card1 + card2 and then if you draw another card your score will be greater than those 2 cards since you have 3 cards now. That is why it is also not entering your if statement.
So I made quite a few changes to my code and now it complies, but I get the wrong totals and it always thinks Player 2 wins, even before it hits "20". For some reason it isn't reading player 1 totalScore until after player 2 has rolled and then it does not calc player 2 turnTotal. When I made changes before, one thing would start working, but another would stop, so I took it back to where I began to have problems once it would compile.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore += dice;
System.out.print("Player 1 turn total is " + turnScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
{
totalScore += turnScore;
}
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
{ do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 += dice2;
System.out.print("Player 2 total is " +turnScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r") && dice != 1); {
totalScore2 += turnScore2;
}
}
if(totalScore2 >= WIN);
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
}
}
}
There is an error in the loop for player2/computer's turn. It's in the first if-else loop, located in the else portion.
input keyboard.nextLine();
should be
input = keyboard.nextLine();
It works fine after correcting that error.
Also, pay close attention to the compilation errors, they will point you towards which lines are generating said error.
Revision:
I think this works the way you intended it to.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore = dice; //removed +=??? think it's only the value of dice roll?
//either way it's used to compute total, which would be redundant if not
totalScore +=turnScore; //added to compute totalScore before turn is over
System.out.print("Player 1 turn total is " + totalScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore); //previously total wasn't computed
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}while(input.equalsIgnoreCase("r"));
//totalScore += turnScore; was removed + curly braces that seemed to attach it to the above while loop
//it isn't needed due to totalScore now being calculated after dice is rolled when !=1(else portion)
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
break; //added to break the loop if player 1 wins
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 = dice2; //removed += ... same as for player 1's turn
totalScore2 += turnScore2; //added totalScore2 calculations.
System.out.print("Player 2 total is " +totalScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r")); //{ <- incorrect brace + fixed loop for dice2 !=1, then removed it :P since you already did a check inside the do-while loop
//totalScore2 += turnScore2; removed, no longer is needed
//}
//} <- not needed nor is the brace that was infront of the do while loop.
if(totalScore2 >= WIN) //removed semicolon since it ended the if statement before it's body
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
if(totalScore>totalScore2) //added loops to check which score is higher and terminate
{
System.out.println("Player 1 Wins!");
break;
}else if(totalScore==totalScore2){
System.out.println("It's a Tie!");
break;
}else if(totalScore<totalScore2){
System.out.println("Player 2 Wins!");
break;
}
}
}
}
I also recommend installing an IDE such as Netbeans or Eclipse. An IDE would make your life much easier, especially with formatting and syntax errors.
public class BlackJack {
public static void main(String args[]) {
String input;
char reDo;
Scanner keyboard = new Scanner (System.in);
Random random = new Random();
int card1 = random.nextInt(10) + 1;
int card2 = random.nextInt(10) + 1;
int card = random.nextInt(10) + 1;
int total1 = card1 + card2;
int total2 = total1 + card;
System.out.print("First cards: " + card1 + ", " + card2 + "\n");
System.out.print("Total: " + total1 + "\n");
boolean loop = true;
while (loop) {
System.out.print("Do you want another card? (y/n): ");
input = keyboard.nextLine();
reDo = input.charAt(0);
if (reDo == 'y' || reDo == 'Y') {
System.out.print("Card: " + card + "\n");
System.out.print("Total: " + total2 + "\n");
} else if (reDo == 'n' || reDo == 'N') {
loop = false;
}
}
}
}
The output is as follows:
First cards: 8, 3
Total: 11
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): y
Card: 7
Total: 18
Do you want another card? (y/n): n
I want to be able to generate a new random card within the loop, display the recurring total, and stop the program. The issue I can't understand is how to use the random.nextInt tool and be able to reuse it more accessibly. Currently its stuck as card1, card2, card, total1, and total2. If I could make them so that I could access them more easily the program would be easier I think to write. The issue is that I can't understand how to repeat the random.nextInt within the while loop.
First put all the cards in a deck.
Then generate a random number between 0 and the number of cards in the deck.
If deck is an ArrayList (for example), you could do
import java.util.*;
public class Main
{
public static void main(String[] args)
{
List<Card> deck = new ArrayList<Card>();
deck.add(new Card(1));
deck.add(new Card(3));
deck.add(new Card(7));
deck.add(new Card(10));
Random randomGenerator = new Random();
System.out.println("Deck 1 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
int randomCard = randomGenerator.nextInt(deck.size());
Card card = deck.remove(randomCard);
System.out.println("Removed a(n) "+card);
}
// you could also do
List<Card> deck2 = new ArrayList<Card>();
deck2.add(new Card(1));
deck2.add(new Card(7));
deck2.add(new Card(3));
deck2.add(new Card(10));
Collections.shuffle(deck2);
System.out.println("Deck 2 tests");
// draw 3 cards:
for (int i = 0; i < 3; i++)
{
Card card = deck2.remove(0);
System.out.println("Removed a(n) "+card);
}
}
}
class Card {
public Card(int i)
{
blackJackValue = i;
}
public int blackJackValue;
public String toString() {
return String.valueOf(blackJackValue);
}
}