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);
}
}
Related
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 :-).
So in my blackjack program when each game ends the program asks you if you would to play again. My main problem right now is that when the new game is started the score counter just keeps adding the new score to the old score instead of resetting to 0. Im not really sure how to fix it. Here are the two classes where the problem is.
Player class:
public class Player{
private String name;
private Card[] hand; // from 2 - 5 cards allowed
private int cardCount,
chips;
public Player()
{
hand = new Card[5];
chips = 5;
cardCount = 0;
}
public Player(String n){
hand = new Card[5];
name = n;
chips = 5;
cardCount = 0;
}
public void acceptACard(Card c){
hand[cardCount] = new Card();
hand[cardCount] = c;
cardCount++;
}
public void showHand(int startCard)
{
for (int i = startCard; i < cardCount; i++){
System.out.print(hand[i] + "\t"); // displays one card from hand
}
}
public int calcScore(){
int cardScore =0;
int total = 0;
boolean hasAce = false;
for(int i=0; i < cardCount; i++){
cardScore = hand[i].getValue();
if (cardScore >=11 && cardScore <=13)
cardScore = 10;
else if (cardScore == 14){
cardScore = 11;
hasAce = true;
}
total += cardScore;}
if (total > 21 && hasAce == true)
total -= 10;
return total;
}
public void incrementChips(){
chips ++;
}
public void decrementChips(){
chips --;
}
public int getChips(){
return chips;
}
}
BlackJack class:
public class BlackJack {
private Player human,
computer;
private Deck deck = new Deck();
Scanner scan = new Scanner(System.in);
public BlackJack(){
human = new Player("");
computer = new Player ("");
}
public void playGame()
{
int cardTotal = 0;
String answer, answer2;
deck.shuffle();
do{
for ( int i = 0; i < 2; i++)
{
human.acceptACard(deck.dealACard());
computer.acceptACard(deck.dealACard());
}
System.out.print(" Human hand: ");
human.showHand(0);
System.out.print("\n Computer hand: ");
computer.showHand(1);
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if(human.calcScore() == 21 && computer.calcScore() < 21)
System.out.println("You win");
else if (computer.calcScore() == 21 && human.calcScore() < 21)
System.out.println("Computer wins!");
else if (computer.calcScore() == 21 && human.calcScore() == 21)
System.out.println("Tie!");
else if (human.calcScore() < 21)
do{
System.out.println("\nWould you like to hit or stay? Type hit or" +
" stay.");
answer = scan.nextLine();
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
}while(cardTotal < 4 && answer.equals("hit"));
determineWinner();
System.out.println("Would you like to play again? Enter yes or no: ");
answer = scan.nextLine();
}while(answer.equals("yes"));
reportGameStatus();
}
public void dealHand(){
int i = 2; int j =2;
human.acceptACard(deck.dealACard());
System.out.println("New card: ");
human.showHand(i++);
while(computer.calcScore() < 17){
computer.acceptACard(deck.dealACard());
System.out.println();
System.out.println("Computer's new card: ");
computer.showHand(j++);
}
}
public void determineWinner(){
System.out.println("\nThe computers total points: " +
computer.calcScore());
System.out.println("Players total points: " + human.calcScore());
if (computer.calcScore() > human.calcScore() && computer.calcScore()<22){
System.out.println("Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (human.calcScore() > computer.calcScore() && human.calcScore()
<22){
System.out.println("You win!!");
human.incrementChips();
computer.decrementChips();
}
else if (human.calcScore() == computer.calcScore() )
System.out.println("Tie!");
else if (human.calcScore() > 21){
System.out.println("You bust! The Computer wins!");
computer.incrementChips();
human.decrementChips();
}
else if (computer.calcScore() > 21){
System.out.println("The Computer busts! You win!");
computer.decrementChips();
human.incrementChips();
}
}
public void reportGameStatus(){
if(computer.getChips() > human.getChips())
System.out.println("Overall winner is the computer!");
else if(human.getChips() > computer.getChips())
System.out.println("You are the overall winner!");
}
}
Any help would be much appreciated.
I think here is your problem:
if(answer.equals("hit"))
{
dealHand();
human.calcScore();
computer.calcScore();
cardTotal ++;
}
Instead of making new Objects you use the old ones and keep their inner state. That means your construktor is not used a second time and therefore your score, hand, chips are not resetted.
How about trying this:
if(answer.equals("hit"))
{
dealHand();
Player human = new Player();
human.calcScore();
Computer computer = new Coputer();
computer.calcScore();
cardTotal ++;
}
Also you have to make a new Deck everytime you start a new game:
Deck deck = new Deck();
Edit:
If you want to keep your chipCount place it in an Object wich will be initialiset in the constructor of your Blackjack class. After that call a function chipcount.setChipcount(chips); if you want to change the chipCount. Obvisoulsly your chipcount-object should have a getter getChipcounts() as well to get the actual chipCount.
It could look like this:
public BlackJack(){
human = new Player("");
computer = new Player ("");
ChipCount chipCount = new Chipcount(0);
}
here is how your object would be:
class ChipCount{
int chipCount;
public ChipCount(int startChips){
this.chipCount = startchips;
}
public void setChips(int chipsToAdd){
this.chipCount = this.chipcount + chipsToAdd;
}
public int getChips(){
return chipCount;
}
}
Before youre asking. Of course you could make two objects (ChipCountPlayer & ChipCountComputer). Also there is the possibility of giving setChips & getChips another argument like:
class ChipCount{
int chipCountPlayer;
int chipCountComp;
public ChipCount(int startChips){
this.chipCountPlayer = startchips;
this.chipCountComp = startchips;
}
public void setChips(int chipsToAdd, String player){
if(player.equals("player")){
this.chipCountPlayer = this.chipcountPlayer + chipsToAdd;
} else if (player.equals("computer")){
this.chipCountComp = this.chipcountComp + chipsToAdd;
}
}
public int getChips(String player){
if(player.equals("player")){
return chipCountPlayer;
} else if (player.equals("computer")){
return chipCountcomp;
}
}
}
that would be the other solution :P
PS: I am not fond of blackjack, does the computer even have chips? Anyway you could replace the comp with another player if you want to further extent your programm :D
This is part of my code for a Black Jack program that I broke apart. This is just the section that deals two cards to the player and then prompts for another card and totals up the sum. My sum messes up every time when the player chooses another card, because my formula will add the new number to the original two cards and now the first two cards and the first new card.
import java.util.Scanner;
import java.util.Random;
public class DealToPlayer
{
public static void main(String[] args)
{
String input;
char choice;
int sum;
int card1;
int card2;
int newCard;
#SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
card1 = randomNumbers.nextInt(13)+1;
card2 = randomNumbers.nextInt(13)+1;
System.out.println("First Card: " +card1 + " Second Card: " +card2);
System.out.println("Would you like another card?");
input = keyboard.nextLine();
choice = input.charAt(0);
do
{
newCard = randomNumbers.nextInt(13)+1;
System.out.println("New card: " +newCard);
sum = card1 + card2 + newCard;
System.out.println("Sum: " +sum);
System.out.println("Would you like another card?");
input = keyboard.nextLine();
choice = input.charAt(0);
}while (choice == 'Y' || choice == 'y');
}
}
just extract the card1 + card2 from the loop :
sum = card1 + card2;
do
{
newCard = randomNumbers.nextInt(13)+1;
System.out.println("New card: " +newCard);
sum = sum + newCard;
System.out.println("Sum: " +sum);
this way each loop will add only the new card value to the sum.
My program has a menu with 3 choices. 1 is to display the deck(if the users enter 1 first a new deck will be displayed). 2 is to shuffle the deck without printing the deck. 3 just exits the program. So for example to print a shuffled deck the user must enter 2 to shuffle then press 1 to display the shuffled deck. I cannot figure out how to print the shuffled deck without printing the new deck.
import java.util.Scanner;
public class Prog4 {
public static void main(String[] args){
double menuOption = 0;
int z = 0;
MyDeck d1 = new MyDeck();
MyCard c;
System.out.println();
while (true){
Scanner option = new Scanner(System.in);
try{
System.out.println("1. Display the deck");
System.out.println("2. Shuffle the cards");
System.out.println("3. Quit");
System.out.print("(Choose a menu 1, 2, or 3 : ");
menuOption = option.nextDouble();
if (menuOption == 1) {
System.out.println("You selected display deck!! ");
while(true){
while(z<=12){
c = d1.printDeck2(z);
System.out.print(c.toString() + " ");
z++;
}
System.out.println();
while(z<=25){
c = d1.printDeck2(z);
System.out.print(c.toString() + " ");
z++;
}
System.out.println();
while(z<=38){
c = d1.printDeck2(z);
System.out.print(c.toString() + " ");
z++;
}
System.out.println();
while(z<=51){
c = d1.printDeck2(z);
System.out.print(c.toString() + " ");
z++;
}
if(z>51)
break;
}
System.out.println();
}
else if(menuOption == 2){
System.out.println("You selected Shuffle the cards!! ");
c = d1.shuffle3();
}
else if(menuOption == 3){
System.out.println("You selected exit!!");
break;
}
else
break;
}
catch (Exception e) {
System.out.println("Invalid menu selected. Please choose menu 1, 2, or 3");
}
}
}
}
public class MyCard {
private int suit;
private int rank;
private String[] suits = {"S","D","H","C"};
private String[] ranks = {"01","02","03","04","05","06","07","08","09","10","11","12","13" };
public MyCard(int suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public int getSuit() {
return suit;
}
public void setSuit(int suit) {
this.suit = suit;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String toString() {
return suits[suit] + "" + ranks[rank];
}
}
import java.util.Random;
public class MyDeck {
private MyCard[] cards;
int i;
int q = 51;
int z = 51;
public MyDeck() {
i = 1;
cards = new MyCard[52];
int x = 0;
for(int t=0;t<=3;t++){
for(int s=0;s<=12;s++){
cards[x] = new MyCard(t,s);
x++;
}
}
}
public MyCard shuffle3(){
Random randomNumber = new Random();
int index = 0;
while(z>0){
index = randomNumber.nextInt(q);
break;
}
MyCard temp = cards[index];
cards[index] = cards[z];
cards[z] = temp;
MyCard temp2 = temp;
z--;
q--;
return temp2;
}
public MyCard printDeck2(int y){
MyCard temp = cards[y];
return temp;
}
}
Rather then create your deck in the first option, have a separate method called something initDeck() which does the deck initialisation.
Then when the option 1 is entered, check the deck is initialised, if not create one, then print it. If it is initialised, just print it.
When option 2 is chosen again check if the deck is initialised, if not create one then shuffle it. If it has been initialised, just shuffle it.
The point is, the method initDeck() should only ever be called once during the run time of your program.
Another option is to use a Singleton pattern
I wrote this without really looking at your code to much... I assumed that your option 1 was creating the deck with all those while loops but really it is just a mess.. its running the same code over just with a println in it. and could be replaced with something like (println condition may need a bit of adjusting) - it should also be within the Deck class and shouldn't need and input arugments:
while (z <= 52) {
c = d1.printDeck2(z);
System.out.print(c.toString() + " ");
if(z%12 == 0)
System.out.println();
z++;
}
From your updated post, it appears that your shuffle method will only swap two cards and you only call it once so check carefully that your print method has actually swapped two cards.
To fix this you need to either rethink your shuffle method or call it x amount of times.
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);
}