I have an assignment in my Java 1 class. It is to create a Black-Jack Game with a Command Line Interface.
However my book only has one page devoted to Command-Line Arguments. This project is an extra credit thing so I guess we are supposed to look elsewhere to find this info. I've finished my program. It runs and works. I'm sure my Code will look clunky to anyone that has been doing this for a while.
Can anyone enlighten me on this topic, the topic being Command Line Interface?
Here is my code:
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
boolean play = true;
while (play == true) {
Game game1 = new Game();
Scanner keyboard = new Scanner(System.in);
Deck deck1 = new Deck();
deck1.createDeck();
deck1.shuffleDeck(deck1.getDeck1());
game1.setDeck(deck1.getDeck2());
System.out.println("Welcome to BLACKJACK!");
System.out.println("------------------------");
System.out.println("Enter 1 to Start: ");
int start = keyboard.nextInt();
if (start == 1) {
deck1.createDeck();
System.out.println("Shuffling Deck");
deck1.shuffleDeck(deck1.getDeck1());
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Shuffling Deck");
System.out.println("Lets Play!");
game1.dealOneCardPlayer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealOneCardPlayer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealoneCardDealer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.dealoneCardDealer(game1.getCardCounter());
game1.setCardCounter(game1.getCardCounter() + 1);
game1.check();
}
while (game1.isEndGame() == false) {
game1.displayPlayer();
game1.turnLoop();
}
if (game1.isEndGame() == true) {
System.out.println("FINAL HANDS");
System.out.println("");
game1.displayPlayer();
System.out.println("");
System.out.println("Do you want to Play again? 1 = yes or 2 = no");
int answer = keyboard.nextInt();
if (answer == 1) {
play = true;
} else if (answer == 2) {
System.out.println("Fine, Go do something else.");
play = false;
}
} else {
System.out.println("Why won't you play with me billy?");
}
}
}
}
public class Card {
private int value;
private String suit;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Card(int value, String suit) {
this.value = value;
this.suit = suit;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
public class Deck {
private Card[] Deck1 = new Card[52];
private Card[] Deck2 = new Card[52];
public Card[] getDeck2() {
return Deck2;
}
// this is important... I think.
public void setDeck2(Card[] Deck2) {
this.Deck2 = Deck2;
}
public Card[] getDeck1() {
return Deck1;
}
public void setDeck1(Card[] Deck1) {
this.Deck1 = Deck1;
}
public Card getOneCard2(int i) {
System.out.println("your drew the " + Deck2[i].getName() + " of " + Deck2[i].getSuit());
return Deck1[2];
}
public Card getOneCard(int i) {
System.out.println("your drew the " + Deck1[i].getName() + " of " + Deck1[i].getSuit());
return Deck1[i];
}
public void setDeck(Card Card, int position) {
Deck1[position] = Card;
}
public void shuffleDeck(Card[] Deck){
for(int i = 0; i < 52 ; i++){
Random rand = new Random();
int position = rand.nextInt((51 - 0) + 1);
Deck2[i] = Deck1[position];
}
}
public void printDeck1(){
for(int i = 0; i < 52 ; i++){
System.out.println(Deck1[i].getName() + " of " + Deck1[i].getSuit() + " In Game Value: " + Deck1[i].getValue() );
}
}
public void createDeck(){
int B;
int value;
String suit;
int deckPosition = 0;
for( B = 1 ; B <= 4 ; B++){
if( B == 1){
suit = "Spades";
}
else if (B == 2){
suit = "Hearts";
}
else if (B == 3){
suit = "Clubs";
}
else {
suit = "Diamonds";
}
for (int i = 1; i <= 13; i++){
value = i;
Card card = new Card(value, suit);
Deck1[deckPosition] = card;
if(Deck1[deckPosition].getValue() == 11){
Deck1[deckPosition].setName("Jack");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 12){
Deck1[deckPosition].setName("Queen");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 13){
Deck1[deckPosition].setName("King");
Deck1[deckPosition].setValue(10);
}
else if(Deck1[deckPosition].getValue() == 1){
Deck1[deckPosition].setName("Ace");
Deck1[deckPosition].setValue(11);
}
else{
Deck1[deckPosition].setName(Integer.toString(Deck1[deckPosition].getValue()));
}
deckPosition++;
}
}
}
}
public class Game {
private Card[] Deck = new Card[52];
private ArrayList<Card> playerHand = new ArrayList<>();
private ArrayList<Card> dealerHand = new ArrayList<>();
private int pValue = 0;
private int dValue = 0;
private int cardCounter = 0;
private boolean endGame = false;
public boolean isEndGame() {
return endGame;
}
public int getCardCounter() {
return cardCounter;
}
public void setCardCounter(int cardCounter) {
this.cardCounter = cardCounter;
}
public int getpValue() {
return pValue;
}
public int getdValue() {
return dValue;
}
public ArrayList<Card> getPlayerHand() {
return playerHand;
}
public ArrayList<Card> getDealerHand() {
return dealerHand;
}
public void dealOneCardPlayer(int i) {
playerHand.add(Deck[i]);
}
public void dealoneCardDealer(int i) {
dealerHand.add(Deck[i]);
}
public void setDealerHand(ArrayList<Card> dealerHand) {
this.dealerHand = dealerHand;
}
public void setDeck(Card[] Deck) {
this.Deck = Deck;
}
public void displayPlayer(){
pValue = 0;
dValue = 0;
System.out.println("---------------------------------------------");
System.out.println("DEALER HAND");
for( int i = 0 ; i < dealerHand.size() ; i++){
System.out.println(dealerHand.get(i).getName() + " of " + dealerHand.get(i).getSuit());
dValue = dValue + dealerHand.get(i).getValue();
}
System.out.println("Dealer Hand Value = " + dValue);
System.out.println("---------------------------------------------");
System.out.println("PLAYER HAND");
for( int i = 0 ; i < playerHand.size() ; i++){
System.out.println(playerHand.get(i).getName() + " of " + playerHand.get(i).getSuit());
pValue = pValue + playerHand.get(i).getValue();
}
System.out.println("Player Hand Value = " + pValue);
System.out.println("");
System.out.println("");
}
public void turnLoop() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Do you want to (H)it, (S)tay, or (C)all?");
String hitstaycall = keyboard.nextLine();
if("h".equals(hitstaycall.toLowerCase())){
playerHand.add(Deck[cardCounter]);
pValue = pValue + Deck[cardCounter].getValue();
cardCounter++;
if ( dValue < 16 ){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else if("s".equals(hitstaycall.toLowerCase())){
if ( dValue < 16 ){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else if("c".equals(hitstaycall.toLowerCase())){
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue < pValue && pValue < 21){
dealerHand.add(Deck[cardCounter]);
dValue = dValue + Deck[cardCounter].getValue();
cardCounter++;
}
if ( pValue > dValue && pValue < 22){
System.out.print("YOU WIN!!!!");
endGame = true;
}
if ( dValue > pValue && dValue < 22){
System.out.println("Dealer Wins!");
endGame = true;
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
else { System.out.println("Hey you.");
}
}
public void check(){
dValue = 0;
pValue = 0;
for( int i = 0 ; i < dealerHand.size() ; i++){
dValue = dValue + dealerHand.get(i).getValue();
}
for( int i = 0 ; i < playerHand.size() ; i++){
pValue = pValue + playerHand.get(i).getValue();
}
if ( dValue > 21 && pValue > 21){
System.out.println("You Lose. Dealer doesn't lose because you bust first. Its the House rules...");
endGame = true;
}
if (pValue == 21 || dValue == 21 ){
System.out.println("BLACKJACK!");
endGame = true;
}
if ( dValue > 21 && pValue < 22){
System.out.println("Dealer BUST. You Win");
endGame = true;
}
if ( pValue > 21 && dValue <22){
System.out.println("You BUST. Dealer Win");
endGame = true;
}
}
}
I think the meaning of "command line interface" here is a mixture of command line arguments and reading from System.in and writing to System.out. ie the user can interface with the program through a command line terminal or window.
Furthermore it probably implies that the user issues commands through that window that are interpreted by the program after reading from System.in.
I guess the term "command" here can be interpreted however you like but you probably have some idea what your instructor would expect.
Related
i have a exercice to do in Java. I need to create a World Cup tournament and the restriction is that the program will restart until my favourite team win. However, if my team didn't win after 20 times, the program stop
The problem is when I try to put the second restriction (20 times max) with a for after the while (true), I always get an infinite loop.
//Q1
String[] teams16 = {"Uruguay", "Portugal", "France", "Argentina", "Brazil", "Mexico",
"Belgium", "Japan", "Spain", "Russia", "Croatia", "Denmark", "Sweden", "Switzerland",
"Colombia", "England"};
//data
Scanner keyboard = new Scanner(System.in);
Random result = new Random();
System.out.print("Enter your favourite team: ");
String team = keyboard.nextLine();
boolean teamwc = false;
// choice of the favourite team
for (int i = 0 ; i < 16 ; i++ ) {
if (teams16[i].equalsIgnoreCase(team)) {
teamwc = true;
}
}
if(teamwc == false) {
System.out.println("Your team is not in the Round of 16 ");
}
// the tournament begins (ROUND OF 16)
while (true) {
if (teamwc == true) {
int z = 0;
String[] winnerof16 = new String[8];
int a = 0;
System.out.print("ROUND OF 16:");
for (int i = 0; i < 16 ; i+=2) {
int score1 = result.nextInt(5);
int score2 = result.nextInt(5);
if (score1 > score2) {
winnerof16 [a] = teams16[i];
}
else if (score1 < score2) {
winnerof16[a] = teams16[i+1];
} else if (score1 == score2) {
Random overtime = new Random();
int ot = overtime.nextInt(2);
if (ot == 0) {
score1++;
winnerof16[a] = teams16[i];
} else if (ot == 1) {
score2++;
winnerof16[a]=teams16[i+1];
}
}
System.out.print("["+teams16[i] +"]"+ " " + score1+":"+score2 + " " + "["+teams16[i+1]+"]" + " ");
a++;
}
System.out.println();
String[] winnerof8 = new String[4];
int b = 0;
System.out.print("QUARTER-FINALS:");
for (int k = 0 ; k < 8 ; k+=2) {
int score3 = result.nextInt(5);
int score4 = result.nextInt(5);
if (score3 > score4) {
winnerof8[b]=winnerof16[k];
}
else if (score3 < score4) {
winnerof8[b] = winnerof16[k+1];
} else if (score3 == score4) {
Random overtime2 = new Random();
int ot2 = overtime2.nextInt(2);
if (ot2 == 0) {
score3++;
winnerof8[b]=winnerof16[k];
} else if (ot2 == 1) {
score4++;
winnerof8[b]=winnerof16[k+1];
}
}
System.out.print("["+winnerof16[k] +"]"+ " " + score3+":"+score4 + " " + "["+winnerof16[k+1]+"]" + " ");
b++;
}
System.out.println();
String[] winnerof4 = new String[2];
int c = 0;
System.out.print("SEMI-FINALS:");
for (int l = 0 ; l < 4 ; l+=2) {
int score5 = result.nextInt(5);
int score6 = result.nextInt(5);
if (score5 > score6) {
winnerof4[c]=winnerof8[l];
}
else if (score5 < score6) {
winnerof4[c] = winnerof8[l+1];
} else if (score5 == score6) {
Random overtime3 = new Random();
int ot3 = overtime3.nextInt(2);
if (ot3 == 0) {
score5++;
winnerof4[c]=winnerof8[l];
} else if (ot3 == 1) {
score6++;
winnerof4[c]=winnerof8[l+1];
}
}
System.out.print("["+winnerof8[l] +"]"+ " " + score5+":"+score6 + " " + "["+winnerof8[l+1]+"]" + " ");
c++;
}
System.out.println();
String[] winnerof2 = new String[1];
int d = 0;
System.out.print("FINALS:");
for (int m = 0 ; m < 2 ; m+=2) {
int score7 = result.nextInt(5);
int score8 = result.nextInt(5);
if (score7 > score8) {
winnerof2[d]=winnerof4[m];
}
else if (score7 < score8) {
winnerof2[d] = winnerof4[m+1];
} else if (score7 == score8) {
Random overtime4 = new Random();
int ot4 = overtime4.nextInt(2);
if (ot4 == 0) {
score7++;
winnerof2[d]=winnerof4[m];
} else if (ot4 == 1) {
score8++;
winnerof2[d]=winnerof4[m+1];
}
}
System.out.print("["+winnerof4[m] +"]"+ " " + score7+":"+score8 + " " + "["+winnerof4[m+1]+"]" + " ");
System.out.println();
}
System.out.println("Tournament: " + z + " The WINNER is: " + winnerof2[d]);
z++;
if (winnerof2[d].equalsIgnoreCase(team)) {
break;
}
}
}
}
}
This is my code before I put the second restriction.
Is there a problem with my code ? How can I put the second restriction ? Thank you
The infinite loop is due to this 2:
while (true) { // it will quit while loop only when an exception raised
if (teamwc == true) { // after this you nowhere assign teamwc == false therefore it is always true
instead of direct assigning True to while loop, use a boolean variable or a condition to quit somewhere:
t = true
while(t):
OR
while n>0:
Hey guys so I'm taking my first Java class ever and am stuck with an error code while trying to compile this program. I attached both classes hoping somewhere he can help me find the error. This is the error I'm receiving:
Error: constructor Card in class Card cannot be applied to given types;
required: char,char
found: no arguments
reason: actual and formal argument lists differ in length
It shows the error is on the line "Card temp= new Card();" under the public void shuffle method. Any help will be greatly appreciated.
import java.util.Random;
import java.util.Scanner;
public class Deck {
private Card [] data;
public Deck()
{
String suits = "HDSC";
String ranks = "A23456789TJQK";
data = new Card[52];
int count = 0;
Card C1;
for (int s = 0; s < suits.length(); s++){
for (int r = 0; r < ranks.length(); r ++)
{
C1 = new Card(ranks.charAt(r), suits.charAt(s));
data[count++] = C1;
}
}
}
//This function display's the whole deck of cards
// Our output should be as below
// AH 2H 3H ... KH
// AS 2H 3S ... KS
// AD 2D 3D ... KD
// AC 2C 3C ... KC
public void display()
{
int index=1;
for (int i=0; i<52; i++)
{
System.out.print(data[i].rank +"" + data[i].suit + " ");
if (index%13 == 0 && i!=0 )
System.out.println();
index++;
}
}
//This function randomly shuffles the deck of cards
public void shuffle()
{
int index;
Random random = new Random();
for (int i = 0; i<52; i++)
{
index = i + random.nextInt(52 - i);
Card temp= new Card();
if (index != i)
{
temp = data[i];
data[i] = data[index];
data[index] = temp;
}
}
System.out.println("Card Shuffled");
}
public void deal()
{
int sum = 0;
int countPrime = 0;
boolean isPrime = false;
for(int i=0; i<52; i++)
{
sum += data[i].getValue(data[i]);
isPrime = checkPrime(sum);
if (isPrime == true)
{
sum = 0;
countPrime++;
if (i==51)
{
System.out.println("Winner in " + countPrime + " Piles");
break;
}
}
if (i==51)
System.out.println("Loser");
}
}
boolean checkPrime(int num)
{
boolean isPrime = true;
for(int j = 2; j <= num/2; ++j)
{
// condition for nonprime number
if(num % j == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
//Display menu
public static int menu() {
System.out.println("\nWelcome to Solitaire Prime!");
System.out.println("1) New Deck");
System.out.println("2) Display Deck");
System.out.println("3) Shuffle Deck");
System.out.println("4) Play Solitaire Prime");
System.out.println("5) Exit");
Scanner in=new Scanner(System.in);
int choice = in.nextInt();
return choice;
}
public static void main(String args[])
{
Deck newDeck = null;
int choice;
do{
//Accepts user input for menu
choice = menu();
if (choice == 1)
{
newDeck = new Deck();
System.out.println("New deck created");
}
else if (choice == 2 )
{
newDeck.display();
}
else if (choice == 3 )
{
newDeck.shuffle();
}
else if (choice == 4 )
{
newDeck.shuffle();
newDeck.deal();
}
else if (choice == 5)
{
System.out.println("Exiting game. Goodbye!");
return;
}
else
System.out.println("Wrong choice! Please try again.");
}while(choice!=5);
}
}
public class Card {
char suit;
char rank;
public Card(char r, char s)
{
rank = r;
suit = s;
}
public void menu()
{
}
public void display(Card C1)
{
char suit = getSuit(C1);
char rank = getRank(C1);
String suitName = "";
String rankName = "";
if (suit == 'S')
suitName = "Spade";
else if (suit == 'H')
suitName = "Hearts";
else if (suit == 'C')
suitName = "Clubs";
else if (suit == 'D')
suitName = "Diamonds";
if (rank == 'A')
rankName = "Ace";
else if (rank == '2')
rankName = "Two";
else if (rank == '3')
rankName = "Three";
else if (rank == '4')
rankName = "Four";
else if (rank == '5')
rankName = "Five";
else if (rank == '6')
rankName = "Six";
else if (rank == '7')
rankName = "Seven";
else if (rank == '8')
rankName = "Eight";
else if (rank == '9')
rankName = "Nine";
else if (rank == '1')
rankName = "Ten";
else if (rank == 'J')
rankName = "Jack";
else if (rank == 'Q')
rankName = "Queen";
else if (rank == 'K')
rankName = "King";
System.out.println(rankName + " of " + suitName);
}
//This method gives the value of a card
public int getValue(Card C1)
{
int value = 0;
if (C1.rank == 'A')
value = 1;
else if (C1.rank == '2')
value = 2;
else if (C1.rank == '3')
value = 3;
else if (C1.rank == '4')
value = 4;
else if (C1.rank == '5')
value = 5;
else if (C1.rank == '6')
value = 6;
else if (C1.rank == '7')
value = 7;
else if (C1.rank == '8')
value = 8;
else if (C1.rank == '9')
value = 9;
else if (C1.rank == '1')
value = 10;
else if (C1.rank == 'J')
value = 10;
else if (C1.rank == 'Q')
value = 10;
else if (C1.rank == 'K')
value = 10;
return value;
}
//This method gives the rank of a card
public char getRank(Card C1)
{
return C1.rank;
}
//This method gives the suit of a card
public char getSuit(Card C1)
{
return C1.suit;
}
}
Your Card class only has a constructor that takes two char arguments; there is no zero-argument constructor defined.
When shuffling, you don't need to create a new instance of Card like you're currently doing here: Card temp= new Card(); Instead of creating a new instance of Card and throwing it away, just assign the shuffled Card value to your temp variable like this:
for (int i = 0; i<52; i++)
{
index = i + random.nextInt(52 - i);
if (index != i)
{
Card temp = data[i];
data[i] = data[index];
data[index] = temp;
}
}
Note that we moved temp into the if-block, since it's only used in that scope.
Paper rock scissors java program.
Ok so the only problem I'm having now is the player's score doesn't update until the second loop around. Any suggestions?
Thanks again Radiodef for your help!!
Updated code below.......
import java.util.Scanner;
public class RPS_Game {
public static void main(String[] args) {
char r = 'R';
char p = 'P';
char s = 'S';
char player1 = 0;
char player2 = 0;
int player1Score = 0;
int player2Score = 0;
int playCount = 0;
Scanner scan = new Scanner(System.in);
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
int winner = winningPlayer(player1, player2);
if(winner == 0) {
System.out.print("\nIt's a tie. Nobody wins!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 1) {
System.out.print("\nPlayer 1 wins!!\n");
System.out.println("\nPlayer 1: " + player1Score++);
System.out.println("\nPlayer 2: " + (player2Score += 0));
}
if(winner == 2) {
System.out.print("\nPlayer 2 wins!!\n");
System.out.println("\nPlayer 1: " + (player1Score += 0));
System.out.println("\nPlayer 2: " + player2Score++);
}
playCount++;
}
}
public static int winningPlayer(int player1, int player2) {
//Player 1 wins
int result = 0;
if(player1 == 'R' && player2 == 'S') {
result = 1;
}
else if(player1 == 'P' && player2 == 'R') {
result = 1;
}
else if(player1 == 'S' && player2 == 'P') {
result = 1;
}
//Player 2 wins
else if(player2 == 'R' && player1 == 'S') {
result = 2;
}
else if(player2 == 'P' && player1 == 'R') {
result = 2;
}
else if(player2 == 'S' && player1 == 'P') {
result = 2;
}
return result;
}
}
Well, it seems like first you just need to move the call in to the loop:
while(playCount < 3) {
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player1 = scan.nextLine().toUpperCase().charAt(0);
System.out.print("Please enter either (R)ock, (P)aper, or (S)iccors: ");
player2 = scan.nextLine().toUpperCase().charAt(0);
// recompute the winner each time
int winner = winningPlayer(player1, player2);
...
}
For keeping a score, you could just have a variable for each player:
int player1Score = 0;
int player2Score = 0;
while (...) {
...
if (winner == 1) {
++player1Score;
}
if (winner == 2) {
++player2Score;
}
}
Or you could do something fancier like use an array:
int[] scores = new int[3];
while (...) {
...
++scores[ winner ];
for (int i = 1; i < scores.length; ++i) {
System.out.printf("Player %d score is %d.\n", i, scores[i]);
}
}
Everything else works fine except I run into an issue of printing out the card the player (if they 'hit' ) as I don't know what card the player draws and which player draws what card, it starts at 8 as the first 7 cards are drawn but I don't know what player gets what and how many. So I tried to have a method to print out the hand of each player but I'm having a LOT of trouble with that could use some help. I want to print the cards the players get in my output. I'll post my Card, Player, and BlackJackGame class as my Dealer class is very similar to player.
Card.java
import java.util.Random;
public class Card
{
private String suit, rank;
private int value;
public Card(String suit, String rank)
{
this.suit = suit;
this.rank = rank;
}
public String getRank()
{
return rank;
}
public int Value()
{
if(rank.equals("2"))
{
value=2;
}
else if(rank.equals("3"))
{
value=3;
}
else if(rank.equals("4"))
{
value=4;
}
else if(rank.equals("5"))
{
value=5;
}
else if(rank.equals("6"))
{
value=6;
}
else if(rank.equals("7"))
{
value=7;
}
else if(rank.equals("8"))
{
value=8;
}
else if(rank.equals("9"))
{
value=9;
}
else if(rank.equals("10"))
{
value=10;
}
else if(rank.equals("A"))
{
Random rand = new Random();
int count = rand.nextInt(1) +1;
if(count == 1)
{
value=11;
}
else
value= 1;
}
else if(rank.equals("Q"))
{
value=10;
}
else if(rank.equals("J"))
{
value=10;
}
else if(rank.equals("K"))
{
value=10;
}
return value;
}
public String toString()
{
return(rank + " of " + suit);
}
}
Player.java
public class Player
{
private int cValue;
private int cCount; //Card count used to count how many 'cards' added
Card[] deck= new Card[52];
private int sum;
public Player()
{
cCount=0;
}
public Card addCard(Card a)
{
deck[cCount] = a;
cCount++;
return a;
}
public int getcCount()
{
return cCount;
}
public int getValue()
{
int total=0;
for(int i=0; i < cCount; i++)
{
total += deck[i].Value();
}
return total;
}
BlackJackGame.java
public class BlackJackGame
{
public static void main(String [] args)
{
Card[] deck = new Card[52];
Player[] player = new Player[3];
int loopcount=0;
String p1result = " ", p2result = " ", p3result = " ", p4result = " ", dresult = " ";
String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
for(int i=0; i<13; i++)
{
for(int x=0; x<4;x++)
{
deck[loopcount] = new Card(suit[x], rank[i]);
loopcount++;
}
}
System.out.println("Shuffling...");
for(int i=0; i< deck.length; i++) //Shuffle
{
Card tmp = deck[i];
int count= (int)(Math.random()* deck.length);
deck[i] = deck[count];
deck[count] = tmp;
}
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
System.out.println("Welcome to our BlackJackGame!");
System.out.println("Welcome Dealer!");
Dealer dealer = new Dealer();
System.out.println("Let's deal the cards!");
player1.addCard(deck[0]);
player2.addCard(deck[1]);
player3.addCard(deck[2]);
System.out.println("And now the Dealer gets his card...");
dealer.addCard(deck[3]);
System.out.println("Now we get our second cards!");
System.out.println("Okay Dealer, deal out the cards!");
player1.addCard(deck[4]);
player2.addCard(deck[5]);
player3.addCard(deck[6]);
dealer.addCard(deck[7]);
int count =8;
int i=0;
do
{
p1result = "";
p2result = "";
p3result = "";
dresult = "";
int dvalue = dealer.getValue();
int p1value = player1.getValue();
int p2value = player2.getValue();
int p3value = player3.getValue();
while(p1value < 17) //hit
{
player1.addCard(deck[count]);
count++;
p1value = player1.getValue();
}
if(p1value > 21)
{
p1result = "Bust!";
}
if(p1value <21 && p1value >17)//stand
{
}
while(p2value < 17)//hit
{
player2.addCard(deck[count]);
count++;
p2value = player2.getValue();
}
if(p2value > 21) //bust
{
p2result = "Bust!";
}
if(p2value <21 && p2value >17) //stand
{
}
while(p3value < 17) //hit
{
player3.addCard(deck[count]);
count++;
p3value = player3.getValue();
}
if( p3value > 21)
{
p3result = "Bust!";
}
if(p3value <21 && p3value >21) //stand
{
}
while(dvalue < 17)
{
dealer.addCard(deck[count]);
count++;
dvalue = dealer.getValue();
}
if(dvalue > 21) //Bust
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
if(p1value == 21 || p1value <21)
{
p1result = "Win!";
}
if(p2value == 21 || p2value <21)
{
p2result = "Win!";
}
if(p3value == 21 || p3value <21 )
{
p3result = "Win!";
}
}
if(dvalue < 21 && dvalue >= 17) //For Dealer values in between
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value > dvalue)
{
p1result = "Win!";
}
if(p1value < dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value > dvalue)
{
p2result = "Win!";
}
if(p2value < dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value > dvalue)
{
p3result = "Win!";
}
if(p3value < dvalue)
{
p3result = "Lose!";
}
}
if(dvalue == 21 )
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value < dvalue || p1value > dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value < dvalue || p2value > dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value < dvalue || p3value > dvalue)
{
p3result = "Lose!";
}
}
System.out.println("The BlackJack Game is Complete: ");
System.out.println("Results: ");
System.out.println("Dealer: " +deck[3] + " " + deck[7] + " " +("total of " +dealer.getValue() ));
System.out.println("Player1: " +deck[0] + " " + deck[4] + " "+("total of " +player1.getValue() )+ ": " +p1result);
System.out.println("Player2: " +deck[1] + " " + deck[5] + " "+("total of " +player2.getValue() )+ ": " +p2result);
System.out.println("Player3: " +deck[2] + " " + deck[6] + " "+("total of " +player3.getValue() )+ ": " +p3result);
i++;
}
while(i <1);
}
}
Example Output:
BlackJack Game is Complete!
Results!
Dealer : 6 of Clubs 8 of Spades total 17
Player1: 2 of Clubs 2 of Spades total 16 Lose!
Player2: Q of Hearts Q of Spades total 20 Win!
Player3: A of Spades 6 of Hearts total 17 Push!
// The Problem is when the cards are printed , I print out the first two cards each player has and the dealer which are known. The problem I run into is if the player or dealer 'hits' as you can see with Player 1 I don't know which cards are hit/ and which player has them and was wondering how to have a method in the Player class that would print the hand of each player including the dealer and the cards they have for my output. That is what I need help with. Everything else works fine.
First, I would suggest using a switch statement instead of all those else ifs for rank, it'll be a lot neater :)
Second, in Blackjack an Ace doesn't have a "random" value of either 1 or 11; it is an 11 unless it being an 11 makes the player bust.
Third, I would consider using a list for the deck. Then all you need to do is "shuffle" the list and when you deal a card, remove the top card from the list and add it to the player's hand. (see Collections.Shuffle)
Now to address the initial question, you should have a List hand in the player class. Then add an extension method to the player class to print the hand; it should look something like this:
public void printHand() {
ListIterator<Card> it = hand.listIterator();
if(it.hasNext())
System.out.print(it.next());
while(it.hasNext())
System.out.print(", " + it.next());
System.out.println();
}
I created this program in my quest to learn Java but every time I run it I get the same cards over and over again. I can't really find the problem, so why aren't my cards random? I don't really get what I'm missing, is my shuffle method incorrect?
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
System.out.println("Are you ready to play BlackJack?");
System.out.println();
playBlackjack();
System.out.println("Thanks for playing!");
}
static boolean playBlackjack() {
Deck deck;
Hand dealerHand;
Hand playerHand;
deck = new Deck();
dealerHand = new Hand();
playerHand = new Hand();
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
System.out.println();
if (dealerHand.getBlackjackValue() == 21) {
System.out.println("The dealer have the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("You have the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("The dealer has Blackjack! The dealer wins!");
return false;
}
if (playerHand.getBlackjackValue() == 21) {
System.out.println("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("User has the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("You have Blackjack. You win.");
return true;
}
while (true) {
// User decides whether to hit or stand
System.out.println();
System.out.println();
System.out.println("Your cards are:");
for ( int i = 0; i < playerHand.getCardCount(); i++ )
System.out.println(" " + playerHand.getCard(i));
System.out.println("The total of your hand is " + playerHand.getBlackjackValue());
System.out.println();
System.out.println("The dealer is showing the " + dealerHand.getCard(0));
System.out.println();
System.out.println("Do you hit(type 0) or stand(type 1)? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice != 0 && choice != 1){
System.out.println("0 or 1 must be inputted to continue ");}
while (choice != 0 && choice != 1);
if ( choice == 1 ) {
break;
}
else {
Card newCard = deck.dealCard();
playerHand.addCard(newCard);
System.out.println();
System.out.println("You hits and your card is the " + newCard);
System.out.println("The total of the hand is now " + playerHand.getBlackjackValue());
if (playerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("Fool of a Took! You went over 21 and busted!");
return false;
}
}
}
//User has stood at this point. Poor fool
System.out.println();
System.out.println("You stand. Wouldn't it be nice to sit sometime?");
System.out.println("The dealer's cards are "+ dealerHand.getCard(0) + " and the " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
System.out.println("The dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("The dealer busted! You win!");
return true;
}
}
System.out.println("The dealer's total is " + dealerHand.getBlackjackValue());
System.out.println();
if (playerHand.getBlackjackValue() == dealerHand.getBlackjackValue()) {
System.out.println("The house always wins on a tie. You lose :(");
return false;
}
else if (dealerHand.getBlackjackValue() >= playerHand.getBlackjackValue()) {
System.out.println("The dealer wins as he has " + dealerHand.getBlackjackValue()
+ " points to your " + playerHand.getBlackjackValue() + "!");
return false;
}
else {
System.out.println("You win because you had " + playerHand.getBlackjackValue()
+ " points while the dealer only had " + dealerHand.getBlackjackValue() + "!");
return true;
}
}
}
package blackjack;
public class Card {
private int suit;
private int rank;
public final static int SPADES = 0, // Codes for the 4 suits.
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;
public Card(int cRank, int cSuit) {
rank = cRank;
suit = cSuit;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public String getSuitString() {
// Return a String representing the card's suit.
// (If the card's suit is invalid, "??" is returned.)
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "I don't even know";
}
}
public String getRankString() {
switch ( rank ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "This is impossible!";
}
}
#Override
public String toString() {
return getRankString() + " of " + getSuitString();
}
}
package blackjack;
public class Deck {
private Card[] deck;
private int cardsUsed;
public Deck() {
deck = new Card[52];
int l = 0;
for ( int suit = 0; suit <= 3; suit++ ) {
for ( int value = 1; value <= 13; value++ ) {
deck[l] = new Card(value,suit);
l++;
}
}
cardsUsed = 0;
}
public void shuffle() {
for ( int i = 51; i > 0; i-- ) {
int rand = (int)(Math.random()*(i+1));
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
}
cardsUsed = 0;
}
public int cardsLeft() {
return 52 - cardsUsed;
}
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
}
package blackjack;
import java.util.*;
public class Hand {
private ArrayList hand;
public Hand() {
hand = new ArrayList();
}
public void clear() {
hand.clear();
}
public void addCard(Card c) {
if (c != null){
hand.add(c);
}
}
public void removeCard(Card c) {
hand.remove(c);
}
public void removeCard(int location) {
if (location >= 0 && location < hand.size()){
hand.remove(location);
}
}
public int getCardCount() {
return hand.size();
}
public Card getCard(int location) {
if (location >= 0 && location < hand.size()){
return (Card)hand.get(location);}
else{
return null;
}
}
public void sortBySuit() {
ArrayList newHand = new ArrayList();
while (hand.size() > 0) {
int pos = 0;
Card c = (Card)hand.get(0);
for (int i = 1; i < hand.size(); i++) {
Card c1 = (Card)hand.get(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit() && c1.getRank() < c.getRank()) ) {
pos = i;
c = c1;
}
}
Object remove = hand.remove(pos);
newHand.add(c);
}
hand = newHand;
}
public int getBlackjackValue() {
int val;
boolean ace;
int cards;
val = 0;
ace = false;
cards = getCardCount();
for ( int i = 0; i < cards; i++ ) {
Card card;
int cardVal;
card = getCard(i);
cardVal = card.getRank();
if (cardVal > 10) {
cardVal = 10;
}
if (cardVal == 1) {
ace = true;
}
val = val + cardVal;
}
if ( ace == true && val + 10 <= 21 ){
val = val + 10;
}
return val;
}
}
It's impossible to tell because you have not shown us the relevant code. However, if your results are not random, it's probably because Deck.dealCard() is not random.
Update
After reading the new code you posted. You are not shuffling your deck after you create it.
It's not random, because Deck::dealCard() is not random.
dealCard is quite strange: when a new Deck is created, cardsUsed is 0, yet you shuffle only if cardsUsed is 52.
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
I think you should move the call to shuffle to the constructor, right after constructing the deck.