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.
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++;
*/
}
}
import java.util.*;
import java.util.Scanner;
public class Assignment2 {
public static void main(String args[]){
Scanner stdin = new Scanner(System.in);
Random random = new Random();
int ran2 = (random.nextInt(10));
int ran1 = (random.nextInt(10));
int total = ran1 + ran2;
char exit = 'y';
System.out.println("First cards: " + ran1 + ", " + ran2);
System.out.println("Total: " + total);
while(exit != 'n' && total < 21){
System.out.println("Do you want another card? (y/n): ");
exit = stdin.next().charAt(0);
if (exit =='n'){
System.out.println("Would you like to play again? (y/n): ");
exit = stdin.next().charAt(0);
if(total > 21 || exit == 'n'){
break;
}
}
int next = random.nextInt(10);
System.out.println("Card: "+ next);
total = total + next;//adds
System.out.println("Total: "+ total);
if(total > 21){
System.out.println("Bust.");
break;
}
if(total == 21){
System.out.println("You win!");
break;
}
}
}
}
i got the game working and all, but if i wanted to play from the beginning to where you get your first cards, how would i do it? after you win or lose how would i make it restart the game? i've been trying to figure this out and still cant find out how do it
Wrap your code in another loop :)
Scanner stdin = new Scanner(System.in);
char exit = 'n';
while( exit != 'n' ) {
// your old code here
System.out.println("Play again ? (y/n):")
exit = stdin.next().charAt(0);
}
I've recently decided that I want to make a program that plays a game called "Nim," which is a game in which you start with a predetermined amount of "sticks" and each player takes turns removing between 1 and 3 sticks. Whoever removes the last stick loses.
Anyway, I have written my program and it compiles and runs almost flawlessly. There's only one small problem. After the game is over, it shows the "good game" screen twice, with the game's very first line appearing in the middle (I'll post screenshots at the end here). It's very strange, and I was just wondering if you guys could give it a look.
I'm cutting a chunk of the program out (only one class, named Cup()), because it's somewhat long, so if you see a class you don't recognize then just ignore it. It's pretty self explanatory what the class does in the program, and it's not where the error is occurring. Here's the code.
class SticksGame
{
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses! Must pick 1 - 3 sticks.");
System.out.println();
do
{
i = r.nextInt(15) + 9;
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
System.out.println("Computer removes " + d + " sticks");
i = i - d;
System.out.println("We now have " + i + " sticks");
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
Any helps are appreciated! Thanks :)
~Andrew
CODE EDITED FOR JANOS
A little late, I know, but here is the FULL GAME for anyone who wants to play! feel free to copy and paste it into your notepad and execute using cmd(YOU MUST KEEP MY NAME AS A COMMENT ON TOP!) :)
//Andrew Mancinelli: 2015
import java.util.*;
import java.io.*;
class Cup
{
private ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
public int count()
{
return c.size();
}
public int select()
{
int index = (int)(c.size() * Math.random());
return c.get(index);
}
public void remove(Integer move)
{
c.remove(move);
}
}
class SticksGame
{
public static void help()
{
System.out.println();
System.out.println("Okay, so here's how it works... The object of the game is to NOT have the last stick. Whoever ends up with the very last stick loses.");
System.out.println();
System.out.println("Rule 1: You will each take turns removing sticks. you may only remove 1, 2, or 3 sticks in a turn");
System.out.println();
System.out.println("Rule 2: The beginning number of sticks is always random between 9 and 24 sticks");
System.out.println();
System.out.println("Rule 3: Whoever chooses the last stick, LOSES!");
System.out.println();
System.out.println("And that's it! Simple, right?");
}
public static void main(String[] args) throws InputMismatchException
{
Random r = new Random();
int score1 = 0, score2 = 0;
Cup c = new Cup();
int j = 0, d = 0, i = 0, k = 0;
boolean b = true;
String exit = "default", inst = "default";
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Sticks Game! Last Stick loses!");
System.out.println();
System.out.println("Need some instructions? Type \"help\" now to see the instructions. Otherwise, press enter to play!");
inst = input.nextLine();
if (inst.equals("help"))
{
help();
System.out.println();
System.out.println("press \"enter\" to begin!");
inst = input.nextLine();
}
do
{
i = r.nextInt(15) + 9;
System.out.println();
System.out.println("We begin with " + i + " sticks");
System.out.println();
while (b == true)
{
System.out.println("Your move");
k = input.nextInt();
if (k > 3)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else if (k < 1)
{
System.out.println("You must select between 1 and 3 sticks");
k = input.nextInt();
}
else
{
j = i;
i = i - k;
if (i <= 0)
{
System.out.println("Computer wins!");
score2 = (score2 + 1);
b = false;
break;
}
else
{
System.out.println("We now have " + i + " sticks.");
}
d = c.select();
i = i - d;
if (i >= 0)
{
System.out.println("Computer removes " + d + " sticks");
System.out.println("We now have " + i + " sticks");
}
if (i <= 0)
{
System.out.println("You Win!");
score1 = (score1 + 1);
b = false;
break;
}
}
}
System.out.println();
System.out.println("Good game!");
System.out.println("Your score: " + score1 + " Computer's Score: " + score2);
System.out.println("Press enter if you'd like to play again. Otherwise, type \"quit\"");
input.nextLine();
exit = input.nextLine();
b = true;
}
while(!"quit".equals(exit));
}
}
The problem is that this condition is always true:
while (exit != "quit");
Because != means "not identical",
and the exit variable and "quit" are not identical.
Use the equals method for checking logical equality.
In this example, change the loop condition to this instead:
while (!"quit".equals(exit));
For your other problem of not properly starting a second game,
you need to reinitialize the state variables,
for example reset b = true.
Lastly, note that input.nextInt() doesn't read the newline character that you pressed when entering a number. So when exit = input.nextLine() runs, it reads that newline character, and doesn't actually give you a chance to type "quit". To solve this, add input.nextLine(); right before exit = input.nextLine();
The unexpected retry was because of the use of input.nextLine(); the program assumed that you already pressed [enter].
From previous work, the two options is to insert one more input.nextline();
input.nextLine();
exit = input.nextLine();
Or use input.next(); instead, although enter will not work for this method so you may need to enter any key or "quit" to exit;
exit = input.next();
This question already has answers here:
How do I get the variable of one method to be a variable in another method for Java?
(4 answers)
Closed 8 years ago.
I'm trying to take the output of another method and use it in another method. I know there are other questions that are similar to mine but the solutions that were in those questions never solved my problem, though they did help a little. Here's where I'm stuck (problem is at rewardBet() method):
class Player {
private ArrayList<Card>hand;
private double cash, bet;
//double cash, bet;
public Player(double theCash)
{
cash = theCash;
hand = new ArrayList<Card>();
bet = 0;
}
public double wagerBet()
{
Scanner in = new Scanner(System.in);
System.out.print("Wager a bet: ");
double bet = in.nextDouble();
cash = cash - bet;
System.out.println("You wagered " + bet + ". " + "Now you have " + cash + " cash left.");
return bet;
}
public void rewardBet()
{
bet = wagerBet(); //this is supposed to be taking whatever the user wagered as a bet in the previous method and
cash = cash + (bet * 2); // apply it to this formula in order to mutate the total cash the player has
System.out.println("You now have " + cash + "cash.");
}
Any suggestions as to how to get this bet variable input to carry over?
EDIT, here's the main method like you guys requested:
class BlackJack {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Deck myDeck = new Deck();
myDeck.shuffle();
Player me = new Player(1000);
Player dealer = new Player(0);
Card c = myDeck.dealCard();
me.wagerBet();
System.out.println("Your first card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
System.out.println("Dealer showing " + c);
dealer.hit(c);
c = myDeck.dealCard();
String answer;
System.out.print("Hit or Stay?");
answer = in.nextLine();
while(answer.equals("Hit") || answer.equals("hit"))
{
System.out.println("Your next card is " + c);
me.hit(c);
c = myDeck.dealCard();
System.out.println("Your total hand is currently " + me.totalHand() + ".");
if(me.totalHand() == 21)
{
System.out.println("You win");
me.rewardBet();
System.exit(0);
}
else if(me.totalHand() < 21)
{
System.out.print("Hit or Stay?");
answer = in.nextLine();
}
else{
System.out.println("Player bust.");
System.exit(0);
}}
while(dealer.totalHand() < 17)
{
System.out.println("Dealer draws " + c);
dealer.hit(c);
c = myDeck.dealCard();
System.out.println("Dealer's total hand is currently " + dealer.totalHand() + ".");
if(dealer.totalHand() == 21)
{
System.out.println("Dealer wins.");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println("Dealer bust. You win.");
me.rewardBet();
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
if(me.totalHand() < dealer.totalHand())
System.out.println("Loooooser");
if(me.totalHand() == dealer.totalHand())
System.out.println("Push. Nobody wins");
}
}
and to clarify my problem, the wagerBet() method asks for a double input from the user in the form of a bet. If the player wins his hand then the rewardBet() method will reward the player, giving him back the amount he bet plus the reward, hence 'bet * 2'. The problem is the rewardBet() method isn't recognizing the 'bet' input at all, I'm trying to figure out how to make it so. So for example I make a bet of 50, so now I have 950 dollars (1000 is default). I win the round so rewardBet() needs to give me 100 dollars. Right now it isn't giving me anything for winning.
Well, one problem is at the very last line of your main method:
if(me.totalHand() > dealer.totalHand())
System.out.println("You win!");
me.rewardBet();
You need to wrap this body in braces - the if statement if only functioning on the print statement. Although this doesn't seem as though it will fix the problem that you've described.
Perhaps you should consider doing a different design altogether, and avoid using so much duplicate code.
BlackJack:
public class BlackJack
{
private Deck deck;
private Player me;
private Player dealer;
public static void main(String[] args)
{
BlackJack game = new BlackJack();
game.run();
}
public BlackJack()
{
deck = new Deck();
deck.shuffle();
me = new Player("Joe", 1000.0);
dealer = new Player("Dealer", 0);
}
public void run()
{
double bet = requestBet(me);
// Deal your first two cards
dealNextCard(me, "Your first card is ");
dealNextCard(me, "Your second card is ");
me.printHandTotal();
// Deal dealer's first card
dealNextCard(dealer, "Dealer showing ");
while(requestHitOrStay())
{
dealNextCard(me, "Your next card is ");
me.printHandTotal();
if(me.totalHand() == 21)
{
System.out.println(me.getName() + " wins!");
rewardBet(me, bet);
System.exit(0);
}
else if(me.totalHand() > 21)
{
System.out.println(me.getName() + " bust!");
System.exit(0);
}
}
while(dealer.totalHand() < 17)
{
dealNextCard(dealer, "Dealer draws ");
dealer.printHandTotal();
if(dealer.totalHand() == 21)
{
System.out.println(dealer.getName() + " wins!");
System.exit(0);
}
else if(dealer.totalHand() > 21)
{
System.out.println(dealer.getName() + " bust. You win!");
rewardBet(me, bet);
System.exit(0);
}
}
if(me.totalHand() > dealer.totalHand())
{
System.out.println("You win!");
rewardBet(me, bet);
}
else if(me.totalHand() < dealer.totalHand())
{
System.out.println("Loooooser");
}
else
{
System.out.println("Push. Nobody wins");
}
}
public boolean requestHitOrStay()
{
System.out.print("Hit or Stay? ");
Scanner in = new Scanner(System.in);
return in.nextLine().toLowerCase().equals("hit");
}
public void dealNextCard(Player p, String prefix)
{
Card c = deck.dealCard();
System.out.println(prefix + c);
p.addCard(c);
}
public double requestBet(Player p)
{
Scanner in = new Scanner(System.in);
double bet = Integer.MAX_VALUE;
while(bet > p.getCash())
{
System.out.print("Wager a bet: ");
bet = in.nextDouble();
}
p.setCash(p.getCash() - bet);
System.out.println(p.getName() + " wagered " + bet + ". " + "Now they have " + p.getCash() + " cash left.");
return bet;
}
public void rewardBet(Player p, double bet)
{
p.setCash(p.getCash() + bet * 2);
System.out.println(p.getName() + " now has " + p.getCash() + " cash.");
}
}
Player:
public class Player
{
private ArrayList<Card> hand;
private double cash;
private String name;
public Player(String playerName, double startingCash)
{
hand = new ArrayList<Card>();
cash = startingCash;
name = playerName;
}
public void addCard(Card c)
{
hand.add(c);
}
public int totalHand()
{
int total = 0;
for(Card c : hand)
{
total += c.getValue();
}
return total;
}
public void printHandTotal()
{
System.out.println(name + "'s' total hand is currently " + totalHand() + ".");
}
public String getName()
{
return name;
}
public double getCash()
{
return cash;
}
public void setCash(double cash)
{
this.cash = cash;
}
}
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);
}