Solved

# method that links an object to a randomly selected number

Posted on 2004-08-17
175 Views
Last Modified: 2010-03-31
Im  sorry you guys I dont have enough knowledge to apply all the answers I am given.  Although, you all have helped me a great deal, I am learning more.   I built a class called cards and created some objects.  Now how do I create a method that links the object to the number that bj.deal() brings back.  For example if bj.deal() brings back a 13 then pcard1 = equals13

import java.io.*;
import java.util.*;

//***************************************************************
// Program that simulates the game of Black Jack between one player and
// a simulated dealer.
//***************************************************************
class Blackjack
{
private Random dealer;

Cards equals1 = new Cards (1, 11, "A");
Cards equals2 = new Cards (2, 2, "2");
Cards equals3 = new Cards (3, 3, "3");
Cards equals4 = new Cards (4, 4, "4");
Cards equals5 = new Cards (5, 5, "5");
Cards equals6 = new Cards (6, 6, "6");
Cards equals7 = new Cards (7, 7, "7");
Cards equals8 = new Cards (8, 8, "8");
Cards equals9 = new Cards (9, 9, "9");
Cards equals10 = new Cards (10, 10, "10");
Cards equals11 = new Cards (11, 10, "J");
Cards equals12 = new Cards (12, 10, "Q");
Cards equals13 = new Cards (13, 10, "K");

public static void main(String args[]) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

final int blackjack = 21;
int pcard1 = 0, pcard2 = 0,pcard3 = 0, pcard4 = 0, pcard5 = 0;
int dcard1 = 0, dcard2 = 0, dcard3 = 0, dcard4 = 0, dcard5 = 0;
int dealer = 0;
int player = 0;
int count = 0;
char face;
char another;

//*************************************************************************
//Dealing first hand
//*************************************************************************
Blackjack bj = new Blackjack();
System.out.println("Player \t Dealer");
pcard1 = bj.deal();
dcard1 = bj.deal();
System.out.println("   "+ pcard1 + "\t"+"   "+ dcard1);

pcard2 = bj.deal();
dcard2 = bj.deal();
System.out.println("   "+ pcard2 +"\t   "+"?");

player = pcard1 + pcard2;
dealer = dcard1 + dcard2;

if (player >= blackjack)
{
if (player != blackjack)
System.out.println("Player busts");

else
{ System.out.println("21, player wins");
System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 +"\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t"+"   "+ dcard2);
System.out.println("   "+player+ "\t   "+dealer);
}
}
if (dealer >= blackjack)
{
if (dealer != blackjack)
System.out.println("Dealer busts");
else
System.out.println("21, dealer wins");
{ System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 +"\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t"+"   "+ dcard2);
System.out.println("   "+player+ "\t   "+dealer);
}
}
//*******************************************************************************
//  Dealing 3rd card to player
//*******************************************************************************
pcard3 = bj.deal();
if ((player < blackjack) && (dealer < blackjack));
{ System.out.print("Would you like another card?  y/n   ");
another = in.readLine().charAt(0);
do
{
if ((another !='y') && (another !='n') && (another !='N') && (another !='Y'))
System.out.print("Please enter y or n, try again:   ");

} while ((another !='n') && (another !='N')& (another !='y') && (another !='Y'));
if ((another != 'n')&&(another !='N'))
player = pcard1 + pcard2 + pcard3;

if (player >= blackjack)
{
if (player != blackjack)
System.out.println("Player busts");
}
else
System.out.println("21, player wins");
}
System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 + "\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t   "+"?");
System.out.println("   "+ pcard3);
System.out.println("   "+player);            pcard3 = bj.deal();

//*********************************************************************************
//    Dealing 4th card to player
//*********************************************************************************
pcard4 = bj.deal();
if ((player < blackjack) && (dealer < blackjack));
{ System.out.print("Would you like another card?  y/n   ");
another = in.readLine().charAt(0);
do
{
if ((another !='y') && (another !='n') && (another !='N') && (another !='Y'))
System.out.print("Please enter y or n, try again:   ");

} while ((another !='n') && (another !='N')& (another !='y') && (another !='Y'));
if ((another != 'n')&&(another !='N'))
player = pcard1 + pcard2 + pcard3 + pcard4;

if (player >= blackjack)
{
if (player != blackjack)
System.out.println("Player busts");
}
else
System.out.println("21, player wins");
}
System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 + "\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t   "+"?");
System.out.println("   "+ pcard3);
System.out.println("   "+ pcard4);
System.out.println("   "+player);

//*********************************************************************************
//    Dealing 5th card to player
//*********************************************************************************
pcard5 = bj.deal();
if ((player < blackjack) && (dealer < blackjack));
{ System.out.print("Would you like another card?  y/n   ");
another = in.readLine().charAt(0);
do
{
if ((another !='y') && (another !='n') && (another !='N') && (another !='Y'))
System.out.print("Please enter y or n, try again:   ");

} while ((another !='n') && (another !='N')& (another !='y') && (another !='Y'));
if ((another != 'n')&&(another !='N'))
player = pcard1 + pcard2 + pcard3 + pcard4 + pcard5;

if (player >= blackjack)
{
if (player != blackjack)
System.out.println("Player busts");
}
else
System.out.println("21, player wins");
}
System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 + "\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t   "+"?");
System.out.println("   "+ pcard3);
System.out.println("   "+ pcard4);
System.out.println("   "+ pcard5);
System.out.println("   "+player);
//***************************************************************************
//   Dealers turn to take cards
//***************************************************************************
if ((another != 'y')&&(another !='Y'))
{player = pcard1 + pcard2;
System.out.println("Player \t Dealer");
System.out.println("   "+ pcard1 +"\t"+"   "+ dcard1);
System.out.println("   "+ pcard2 +"\t"+"   "+ dcard2);
System.out.println(player+"\t"+dealer);
}
} // method main
//****************************************************************************
//  instantiate a Blackjack instance
//****************************************************************************
public Blackjack()
{
dealer = new Random();
} // method Blackjack

//****************************************************************************
// method to return # from 1 to 13
//****************************************************************************
public int deal()
{
return dealer.nextInt(13) + 1;
} // method deal

//****************************************************************************
//create a deck of cards
//****************************************************************************
public class Cards
{
private int number;
private int value;
private String face;

public cards (String face, int number, int value)
}
//****************************************************************************
//method to show face of card
//*****************************************************************************
0
Question by:hedge243
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• Learn & ask questions
12 Comments

LVL 3

Expert Comment

ID: 11824215
Firstly there is a much better way of handling the dealing of the cards. Cuz at the moment you only have an option of going to 5 cards and the player could get a king and four aces then he still only has 14 so he might want to go one more you see. So you never know exactly how many there would be.

Thus I am going to advice but not correct you on a better way it should be done. Hint: take a look at dynamic collection classes.

Ok then to get your problem sorted out you would need to do something better with the cards as well currently you have about 13 of them all taking up cumbersome space. What you could do is add them in a set of 2-dimensional matix's that would act as lookup tables. This is a verry fast and efficient way of doing it since you can create the set from the beginning and it is verry fast to just loop through the matrix and find what you want. Then all you need do is dump the cards dealt to the player and the dealer into those dynamic collections that I talked about.

give me a min and I will quickly get some code together for you if you want it.
0

LVL 86

Expert Comment

ID: 11824280
>>Hint: take a look at dynamic collection classes

And i mentioned that in one of your earlier questions ;-)
0

LVL 3

Expert Comment

ID: 11824438
Give me another 30 or so minutes and I will have a better solution for you. Just checking out the code properly.

Also when you are getting ready to deal the first hand you do not need to check weather the user is blackhjack or not since he doesn't have a score yet.
0

Author Comment

ID: 11824650
some code would be great...some how worked into that simple inefficient code I wrote.
0

LVL 2

Expert Comment

ID: 11824702
The code you supplied looks like it is missing lots of stuff....

It doesnt seem like you are truly simulating a deck of cards here

Heres a quick and dirty job of the classes....you can add the game play

import java.util.*;

public class BlackJack{

BlackJack(){
Deck deck = new Deck();
// game play logic here
}

public static void main(String[] args){
BlackJack bj = new BlackJack();
}
}

class Card{
private int value1;  // Ace is 1 or 11, the rest of the card would have value1, and value2 the same
private int value2;

private int suit;
private int rank; //1..13
public Card(int value1, int value2, int suit, int rank){
this.value1 = value1;
this.value2 = value2;
this.suit = suit;
this.rank = rank;
}
// getters and setters

public String getFace(){
switch (rank) {
case 1 : return "A";
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10 : return Integer.toString(rank);
case 11 : return "J";
case 12 : return "Q";
case 13 : return "K";
default : return null;
}
}
}

class Deck{

private Vector cards;

public Deck(){
cards = new Vector(52);
for (int suit=0;suit<=3;suit++){
for (int rank=1;rank<=13;rank++){
Card card = new Card(rank, ((rank==1)?11:rank),suit,rank);
cards.addElement(card);
}
}
}

public Card dealCard()
throws Exception{
Card result = null;
if (cards.size() > 0) {
int seed = new Random().nextInt(cards.size());

result = (Card)(cards.remove(seed));
} else {
throw new Exception("Deck is gone!");
}
return result;
}
}

0

LVL 3

Expert Comment

ID: 11825815
I have broken it up into four classes to make it simpler and easyer to work with and to use proper abstraction methedology. Each of them needs to be in their own .java file so I will post them in diffirent posts.

1. The first is an abstract class called Actor. It will make out the corner stone of the users that play the game (player/dealer).
2. The second and third ones are called User and Dealer respectively and extends from the Actor class
3. The fourth class is the main one which will handel allo of the logic and gameplay.

I know it isn't really what you have asked for but you are going at it in totally the wrong way. It is better to get the design right and not struggel with things like matching diffirent items with each other than to bash right away and hit the wall at a later stage.

I have also talked about 2D-marixs to hold the cards but there is a much better way still especially since all you need is the faces of the cards and the accumulative score of the user and the dealer. This thus lends it to a single int value for the score and a collection class to hold the faces. The easyest collection class to use is a java.util.Vector and that is just what I did. You can go and check all of it's specs on your JDK API specifications if you want.
0

LVL 3

Expert Comment

ID: 11825822
/*
* Actor.java
*/

import java.util.Random;
import java.util.Vector;

/*
* A simple abstract class from which contains common functionality for all
* actors on the table
*/
public abstract class Actor {

/*
* a java.util.Vector containing the faces of the cards the actor has drawn
*/
Vector cards = null;

/*
* the actor's score
*/
int score = 0;

/*
* The random generator that we will be using
*/
Random ran = null;

/*
* instantiate a new Actor
*/
public Actor() {
cards = new Vector();
ran = new Random();
}

/*
* returns the actor's score
*/
public int getScore() {
return score;
}

/*
* return the face of a single card
*/
public String getCardFace(int card) {
String temp = null;
switch (card) {
case (1):
temp = "A";
break;
case (2):
case (3):
case (4):
case (5):
case (6):
case (7):
case (8):
case (9):
case (10):
temp = "" + card;
break;
case (11):
temp = "J";
break;
case (12):
temp = "Q";
break;
case (13):
temp = "K";
break;
}
return temp;
}

/*
* return an array containing the faces of all the cards the user has drawn
*/
public String[] getCardFaces() {
String[] temp = new String[cards.size()];
for (int i = 0; i < cards.size(); i++) {
temp[i] = (String) cards.get(i);
}
return temp;
}

/*
* return the value of a specific card
*/
int getCardValue(int card) {
int temp = 0;
switch (card) {
case (1):
temp = 11;
break;
case (2):
case (3):
case (4):
case (5):
case (6):
case (7):
case (8):
case (9):
case (10):
temp = card;
break;
case (11):
temp = 10;
break;
case (12):
temp = 10;
break;
case (13):
temp = 10;
break;

}
return temp;
}

/*
* draw a card and store the face of the card in a java.util.Vector class
* object
*/
public void drawCard() {
int tmp = ran.nextInt(12) + 1;
String face = getCardFace(tmp);
cards.addElement(face);
score += getCardValue(tmp);
}

/*
* this is to be overridden by it's children and it is where the logic of
* the user or dealer will take place
*/
public abstract boolean deal(boolean choice);
}
0

LVL 3

Expert Comment

ID: 11825826
/*
* User.java
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
* Created on Aug 17, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/

/**
* @author Kostaki
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class User extends Actor {

BufferedReader in = null;

/**
* Here we will need to initialize the input stream
*/
public User() {
super();
in = new BufferedReader(new InputStreamReader(System.in));
}

/*
* Deal a card for the User
*/
public boolean deal(boolean choice) {
// TODO Auto-generated method stub
try {
boolean drawACard = false;
char cTemp = ' ';
if (choice) {
System.out.print("Would you like another card?  y/n :");
cTemp = in.readLine().toUpperCase().charAt(0);
}
if ((!choice) || (cTemp == 'Y')) {
super.drawCard();
} else
return false;

} catch (IOException e) {
return false;
}
return true;
}
}
0

LVL 3

Expert Comment

ID: 11825836
/*
* Dealer.java
*/

/*
* A Classa to simulate the dealer
*/
public class Dealer extends Actor {

/**
* For the dealer we don't need to do anything here
*/
public Dealer() {
super();
}

/*
* Deal a card for the dealer
*/
public boolean deal(boolean choice) {
boolean drawACard = false;
if ((!choice) || (super.score < 18)) {
if (choice) {
System.out.print("Dealer is drawing another card\n");
}
super.drawCard();
} else
return false;
return true;
}

}
0

LVL 3

Expert Comment

ID: 11825845
/*
* Blackjack.java
*/

import java.io.IOException;

/**
* Program that simulates the game of Black Jack between one player and a
* simulated dealer.
*/
class Blackjack {
/** The dealer */
private Actor dealer = null;

/** The user */
private Actor user = null;

/**
* the number to het the closest to
*/
final static int bust = 21;

/*
* Shows us weather the user has finished playing
*/
boolean userFinished = false;

/*
* Shows us weather the dealer has finished playing
*/
boolean dealerFinished = false;

/**
* Instantiate a Blackjack instance
*/
public Blackjack() {
this.dealer = new Dealer();
this.user = new User();
} // method Blackjack

/*
* the main game logic happens here.
*/
public void playGame() {
System.out.println("Welcome To BlackJack\nNow dealing first hand\n");
user.deal(false);
dealer.deal(false);
System.out.println("Now dealing second hand\n");
user.deal(false);
dealer.deal(false);
showUserHand();
showDealerHand();
while ((userFinished != true) || (dealerFinished != true)) {
if (!userFinished) {
userFinished = !user.deal(true);
}
showUserHand();
if (!dealerFinished) {
dealerFinished = !dealer.deal(true);
}
showDealerHand();
}
if ((user.getScore() > bust) || (user.getScore() < dealer.getScore())
|| (user.getScore() == dealer.getScore())) {
//user lost the game
System.out.println("\n\n-------------------------------\n"
+ "Unfortunately you have the game\n"
+ "-------------------------------\n");
} else if ((dealer.getScore() > bust)
|| (user.getScore() > dealer.getScore())) {
//dealer lost the game
System.out.println("\n\n----------------------------\n"
+ "The Congratulations you won the game\n"
+ "----------------------------\n");
}
try {
System.in.read();
} catch (IOException e) {

}
}

/*
* Show the user's hand and check to see wether he is bust/21 or not
*/
private void showUserHand() {
System.out.println("User hand\n");
String[] tmp = user.getCardFaces();
for (int i = 0; i < tmp.length; i++) {
System.out.print(tmp[i] + " - ");
}
System.out.println();
if (user.getScore() > bust) {
System.out.println("The user is bust: " + user.getScore());
userFinished = true;
} else if (user.getScore() == bust) {
System.out.println("The user has 21");
dealerFinished = true;
userFinished = true;
} else {
System.out.println("The user has: " + user.getScore() + "\n");
}
System.out.println("\n");
}

/*
* Show the dealer's hand and check to see wether he is bust/21 or not
*/
private void showDealerHand() {
System.out.println("Dealer hand\n");
String[] tmp = dealer.getCardFaces();
for (int i = 0; i < tmp.length; i++) {
System.out.print(tmp[i] + " - ");
}
System.out.println();
if (dealer.getScore() > bust) {
System.out.println("The dealer is bust: " + dealer.getScore()
+ "\n");
dealerFinished = true;
} else if (dealer.getScore() == bust) {
System.out.println("The dealer has 21");
dealerFinished = true;
userFinished = true;
} else {
System.out.println("The dealer has: " + dealer.getScore());
}
System.out.println("\n");
}

/*
* entry point into the game
*/
public static void main(String args[]) throws IOException {
Blackjack bj = new Blackjack();
bj.playGame();
}
}
0

LVL 3

Accepted Solution

RuadRauFlessa earned 500 total points
ID: 11825864
Note that there is still room for improvement since we are not checking weather the user would like to use an "A" for a 1 or 11 which could happen. Also it could be modified in such a way that a user could also split the cards when he get's two cards of the same type. The later would take a bit more work than the first but it is doable on the design.
0

LVL 3

Expert Comment

ID: 11879896
Hey thanks. Hope this helps you in making future design desisions.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

### Suggested Solutions

Title # Comments Views Activity
numbers ascending pyramid 101 265
eclipse console opening separately 2 50
using executorService 3 21
Which is best Image Resizing Web service 11 42
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues undeâ€¦
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different dâ€¦
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Downâ€¦
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arrâ€¦
###### Suggested Courses
Course of the Month4 days, 11 hours left to enroll

#### 739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.