I have to write a program to play a game of poker between two 'human' players. I have the main method (dealer) set up to ask for the first player's bet but I haven't been able to figure out how to call upon the Deck class to the deal method. I tried deck.deal(), etc. but nothing seems to go through. Ill post the classes that are involved below and I've taken note of where the code should call upon the deck in the Dealer class
public class Dealer
{
private Deck deck;
private Player[] players;
private String n;
Scanner scan = new Scanner(System.in);
public static final int NUMBER_OF_PLAYERS = 2;
/**
* Default constructor - creates and populates the Player array and the
* Deck object.
*/
public Dealer()
{
players = new Player[ NUMBER_OF_PLAYERS ]; //IMPORTANT players is the array
deck = new Deck();
// populate the array of players
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play()
{
System.out.println("Welcome to Poker!");
//Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players[0] = new Player(name);
players[0].getName(name);
//Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players[1] = new Player(name);
players[1].getName(name);
//First Player Goes
System.out.println(players[0].getName(n) + "'s Turn\n");
//Bet
System.out.println("Enter bet: ");
int bet = players[0].getBet(); //IMPORTANT players is the array and can call Player method as own
//Able to bet?
while(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 20;
if(!players[0].bet(bet) || !players[1].bet(bet))
{
bet = 1;
}
}
//Draw Cards/Deck
//*****NEED TO DEAL CARDS HERE*****
//*****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
//Compare
//Add to winner
//Add to loser
//Winner Goes ^^
} // method play
}
public class Deck
{
private int pointer = 0; // indicates the current position in the deck.
// This should begin with 0 (the first call)
// and increment every time a card is dealt.
private Card deck[] = new Card[CARDS_IN_DECK];
private Card tempDeck[] = new Card[CARDS_IN_DECK];
private Card Cards[] = new Card[5];
public static final int CARDS_IN_DECK = 52;
/**
* Instantiate an array of Cards and populate the array with 52 Card
* objects. The face values of the cards should be between 2 - 14.
* Values 2 - 10 represent the number cards. Values 11 - 14 represent
* Jack, Queen, King, and Ace, respectively. The suits should be as
* follows: 100 = Clubs, 200 = Diamonds, 300 = Hearts, and 400 = Spades.
* See the Card class for more information.
*
* You should both shuffle and cut the cards before this method
* concludes.
*/
public Deck()
{
int i = 0;
for(int a = 1; a <= 5; a++)
{
for(int b = 2; b <=14; b++)
{
deck[i] = new Card(a,b);
}
}
shuffle();
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random
* or fixed) and re-arrange the cards. For example, if you choose to
* cut at position 26, then the 27th - 52nd cards will be placed in the
* 1st - 26th positions. The 1st - 26th cards will be placed in the
* 27th - 52nd positions.
*/
public void cut()
{
int cut = 26;
int a = 0;
int b = 0;
for(int i = 0 ; i<cut; i++)
{
tempDeck[i] = new Card(a,b);
tempDeck[i] = deck[i+26];
tempDeck[i+26] = deck[i];
}
deck = tempDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return
* these in an array. You will need to maintain a pointer that lets
* you know where you are in the deck. You should make sure also
* to reshuffle and cut the deck and start over if there are not enough
* cards left to deal a hand.
*
* #return an array of 5 cards
*/
public Card[] deal(int[] args)
{
int i = 0;
int a = 0;
int b = 0;
Cards[i] = new Card(a,b);
for(i = 0; i < 1; i++)
{
Cards[pointer] = deck[pointer];
pointer++;
}
return Cards;
// this is a stub only - replace this!!!!
} // method deal
/**
* Get a card from the deck
*
* #param the position of the card you are retrieving
* #return the card object
*/
public Card getCard( int card )
{
Card oneCard = deck[pointer];
deck[pointer] = null;
pointer +=1;
return oneCard; // this is a stub only - replace this!!!
} // method getCard
/**
* Shuffle the deck. Randomly re-arrange the cards in the deck. There
* are plenty of algorithms for doing this - check out Google!!!
*/
public void shuffle()
{
int i, j, k;
int n = 15;
for ( k = 0; k < n; k++ )
{
i = (int) ( CARDS_IN_DECK * Math.random() ); // Pick 2 random cards
j = (int) ( CARDS_IN_DECK * Math.random() ); // in the deck
tempDeck[j] = deck[i];
tempDeck[i] = deck[j];
deck = tempDeck;
}
pointer = 0; // Reset current card to deal
} // end shuffle
} // class Deck
public class Player
{
private int bet;
private int chips;
private int totalChips = 0;
private Hand hand;
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the player's name
*/
public Player( String n )
{
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that
* the player has by the number of chips bet. Do not allow bets if
* there are not enough chips left.
*
* #param the number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet( int bet )
{
int chipsAB;
boolean canBet;
//Get Bet
getBet();
//See if player has enough chips for bet
if(totalChips >= bet)
{
canBet = true;
}
else
{
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/ //DONE
public int getBet()
{
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips())
{
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips()
{
for(int i = 0; i<1; )
{
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips()
{
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public Hand getHand()
{
return new Hand(); // this is a stub only - replace this!!!!
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName(String name)
{
String n = name;
return n; // this is a stub only - replace this!!!!
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon()
{
boolean won = false;
if(chips == 0)
{
won = true;
}
return won; // this is a stub - replace this!!!
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the
* Dealer)
*
* #param the hand dealt by the dealer
*/
public void setHand( Hand h )
{
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString()
{
String nameChips;
nameChips = (name + totalChips);
return nameChips; // this is a stub only - replace this!!!
} // method toString
/**
* We won the hand, so increase chips
*
* #param the number of chips won
*/
public int winHand()
{
int chipsAB = 0;
//if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
//else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
The code compiles for me, but I had to
create a class called Card with a constructor Card(int a, int b)
create a class called Hand
ignore the Javadoc errors.
After #param you should have the name of the parameter not the ...
The main method wasn't included, but other than that it compiles with a few changes.
I think I can get you going in the right direction but I don't have time to do all the work. I went a bit further and used Java collections to clarify / ease some of the use. A bunch of code updates here. Key points are Suit enum, Collections.shuffle, use of ArrayLists for the deck and hands, and the changes in the cut function. There is also a lot of opportunity for more error and bounds checking.
Stylistically, I'd suggest thinking about your object layout. Dealer is a specialization of Player, shuffle and cut might better be methods on Dealer (a Deck doesn't do those things to itself). Anyhow, for this update I didn't touch those things, just something to be aware of.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Dealer {
public static final int NUMBER_OF_PLAYERS = 2;
private Deck deck;
private List<Player> players = new ArrayList<Player>(NUMBER_OF_PLAYERS);
Scanner scan = new Scanner(System.in);
/**
* Default constructor - creates and populates the Player array and the Deck object.
*/
public Dealer() {
deck = new Deck();
} // constructor
/**
* Outermost level of abstraction for the poker game
*/
public void play() {
System.out.println("Welcome to Poker!");
// Getting First Names
System.out.println("\nEnter first player's name: ");
String name = scan.nextLine();
players.add(new Player(name));
// Getting Second Name
System.out.println("Enter second player's name: ");
name = scan.nextLine();
players.add(new Player(name));
// First Player Goes
System.out.println(players.get(0).getName() + "'s Turn\n");
// Bet
System.out.println("Enter bet: ");
int bet = players.get(0).getBet();
// Able to bet?
while (!players.get(0).bet(bet) || !players.get(1).bet(bet)) {
bet = 20;
if (!players.get(0).bet(bet) || !players.get(0).bet(bet)) {
bet = 1;
}
}
// Draw Cards/Deck
// *****NEED TO DEAL CARDS HERE*****
// *****DEAL AN ARRAY OF CARD[5] TO EACH PLAYERS[0] AND [1]******
for (Player player : players) {
player.setHand(deck.deal(5));
}
// Compare
// Add to winner
// Add to loser
// Winner Goes ^^
} // method play
}
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Player {
private int chips;
private int totalChips = 0;
private List<Card> hand = new ArrayList<Card>();
private String name;
public static final int START_CHIPS = 100;
public static final int WINNING_CHIPS = 200;
Scanner scan = new Scanner(System.in);
/**
* Sets the player's name and the starting number of chips.
*
* #param the
* player's name
*/
public Player(String n) {
name = n;
totalChips = START_CHIPS;
} // constructor
/**
* Sets the amount of the bet and decreases the number of chips that the player has by the number of chips bet. Do not allow
* bets if there are not enough chips left.
*
* #param the
* number of chips bet
* #return true if the bet was successful (there were enough chips)
*/
public boolean bet(int bet) {
boolean canBet;
// Get Bet
getBet();
// See if player has enough chips for bet
if (totalChips >= bet) {
canBet = true;
} else {
canBet = false;
}
return canBet; // this is a stub only - replace this!!!!
} // method bet
/**
* Return the number of chips bet
*
* #return the number of chips bet
*/
// DONE
public int getBet() {
int bet;
bet = scan.nextInt();
while (bet < 1 || bet > getChips()) {
System.out.println("Error. Re-enter bet: ");
bet = scan.nextInt();
}
return bet; // this is a stub only - replace this!!!!
} // method getBet
/**
* Return the number of chips currently held
*
* #return the number of chips held
*/
public int getChips() {
for (int i = 0; i < 1;) {
totalChips = START_CHIPS;
}
return totalChips; // this is a stub only - replace this!!!!
} // method getChips
public int setChips() {
int playersChips = getChips();
return playersChips;
}
/**
* Return the player's hand
*
* #return the player's hand object
*/
public List<Card> getHand() {
return hand;
} // method getHand
/**
* Return the player's name
*
* #return the player's name
*/
public String getName() {
return name;
} // method getName
/**
* Indicates whether this player has won
*
* #return true if the player has more than the number of winning points
*/
public boolean hasWon() {
return (chips > WINNING_CHIPS);
} // method hasWon
/**
* Set the Hand object to the incoming Hand object (this comes from the Dealer)
*
* #param the
* hand dealt by the dealer
*/
public void setHand(List<Card> dealtHand) {
hand = dealtHand;
} // method setHand
/**
* Return the player's name & the number of chips
*
* #return the players name & number of chips
*/
public String toString() {
return "Name: " + name + ", Chips: " + chips;
} // method toString
/**
* We won the hand, so increase chips
*
* #param the
* number of chips won
*/
public int winHand() {
int chipsAB = 0;
// if(hand.beats(other))
{
chipsAB = getChips() + getBet();
}
// else
chipsAB = getChips() - getBet();
return chipsAB;
} // method winHand
} // class Player
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Deck {
public static final int CARDS_IN_DECK = 52;
private List<Card> deck = new ArrayList<Card>(CARDS_IN_DECK);
/**
* Constructor
*
* Instantiate an array of Cards and populate the array with 52 Card objects. The face values of the cards should be between 2 -
* 14. Values 2 - 10 represent the number cards. Values 11 - 14 represent Jack, Queen, King, and Ace, respectively.
*
* You should both shuffle and cut the cards before this method concludes.
*/
public Deck() {
for (Suit suit : Suit.values()) {
// I made the Ace equal to 1, but it's just preference
for (int value = 2; value <= 14; value++) {
deck.add(new Card(suit, value));
}
}
Collections.shuffle(deck);
cut();
} // default constructor
/**
* Cut the deck. Choose a point in the deck (this can be either random or fixed) and re-arrange the cards. For example, if you
* choose to cut at position 26, then the 27th - 52nd cards will be placed in the 1st - 26th positions. The 1st - 26th cards
* will be placed in the 27th - 52nd positions.
*/
public void cut() {
Random rand = new Random();
int cutPoint = rand.nextInt(deck.size()) + 1;
List<Card> newDeck = new ArrayList<Card>(deck.size());
newDeck.addAll(deck.subList(cutPoint, deck.size()));
newDeck.addAll(deck.subList(0, cutPoint));
deck = newDeck;
}
// method cut
/**
* Deal 5 cards from the deck. Deal out the next 5 cards and return these in an array. You will need to maintain a pointer that
* lets you know where you are in the deck. You should make sure also to reshuffle and cut the deck and start over if there are
* not enough cards left to deal a hand.
*
* #return an array of 5 cards
*/
public List<Card> deal(int size) {
List<Card> hand = new ArrayList<Card>(size);
hand.add(deck.remove(0));
return hand;
} // method deal
/**
* Get a card from the deck
*
* #param the
* position of the card you are retrieving
* #return the card object
*/
public Card getCard(int position) {
if (position >= 0 && position < deck.size()) {
return deck.remove(position);
}
else {
return null; // or throw an exception, or print an error or whatever
}
} // method getCard
} // class Deck
public class Card {
private Suit suit;
private int value;
public Card(Suit suit, int value) {
this.suit = suit;
this.value = value;
}
public Suit getSuit() {
return suit;
}
public int getValue() {
return value;
}
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}
Related
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 3 years ago.
I am not able to print out the info of the candy bar. Whenever I try to use the method I get an error: cannot find symbol-method printINFO.
I have tried using n.printInfo() and system.out.println(n.printinfo()), but still it doesnt work. What can I do?
Method class:
public class CandyBar
{
public enum Color
{
BLUE, BROWN, GOLD, GREEN, ORANGE,
PURPLE, RED, SILVER, WHITE, YELLOW
}
// instance variables
private String name;
private double weight;
private Color wrapper;
/**
* Constructor for objects of class CandyBar
*/
public CandyBar(String n, Color c, double w)
{
this.name = n;
this.weight = w;
this.wrapper = c;
}
public String getName()
{
return this.name;
}
public double getWeight()
{
return this.weight;
}
public Color getWrapperColor()
{
return this.wrapper;
}
public void printInfo()
{
System.out.println(this.name);
System.out.printf("%.1f oz with a ", this.weight);
System.out.println(this.wrapper + " wrapper");
}
}
Main class:
import java.util.ArrayList;
public class Lab16
{
public static void main(String[] args)
{
ArrayList<CandyBar> bars = new ArrayList<CandyBar>();
addCandyBarsToList(bars);
/**
* Use the methods you wrote below to answer all of
* the following questions.
*/
/**
* Part A:
*/
/**
* Is Twix in the list?
* If so, print all information about it.
* If not, print a message to the user.
*/
/**
* Is Mounds in the list?
* If so, print all information about it.
* If not, print a message to the user.
*/
/**
* Part B:
*/
/**
* Print all the names of candy bars with yellow wrappers.
*/
/**
* Part C:
*/
/**
* Count how many candy bars are 1.75 oz or more.
*/
/**
* Part D:
*/
/**
* Is there a candy bar that is 1.86 oz?
* If so, print the information.
* If not, print a message to the user.
* Write a binary search method to get the answer.
*/
}
/**
* This method searches a list to find a candy bar by name.
*
* #param list the list to search
* #param n a name to find
* #return the index of the candy bar
*/
public static int findCandyBar(ArrayList<CandyBar> list, String n)
{
for(int i = 0; i < list.size(); i++){
if(list.get(i).getName() == n){
return n.printInfo(i);
}else{
System.out.println("The list doesnt have that Candy");
}
}
return 1;
}
/**
* This method prints the names of the candy bars that have a certain
* wrapper color.
*
* #param list the list to search
* #param c the color wrapper to find
*/
public static void findByColor(ArrayList<CandyBar> list, CandyBar.Color c)
{
}
/**
* This method counts the number of candy bars that weigh greater than
* or equal to the weight input parameter.
*
* #param list the list to search
* #param w the weight to compare to
* #return the count of candy bars
*/
public static int countByWeight(ArrayList<CandyBar> list, double weight)
{
return 0;
}
/**
* This method searches a list using binary search.
*
* #param list the list to search
* #param first the first index
* #param last the last index
* #param w the value to search for
* #return the index of the candy bar
*/
public static int binaryFind(ArrayList<CandyBar> list, int first, int last, double w)
{
return -1;
}
/**
* This method adds candy bars to a list.
*
* #param list the list to add to
*/
public static void addCandyBarsToList(ArrayList<CandyBar> list)
{
CandyBar kitkat = new CandyBar("KitKat", CandyBar.Color.RED, 1.5);
list.add(kitkat);
CandyBar grand = new CandyBar("One-hundred Grand", CandyBar.Color.RED, 1.5);
list.add(grand);
CandyBar crunch = new CandyBar("Crunch", CandyBar.Color.BLUE, 1.55);
list.add(crunch);
CandyBar hershey = new CandyBar("Hershey", CandyBar.Color.BROWN, 1.55);
list.add(hershey);
CandyBar krackel = new CandyBar("Krackel", CandyBar.Color.RED, 1.55);
list.add(krackel);
CandyBar caramello = new CandyBar("Caramello", CandyBar.Color.PURPLE, 1.6);
list.add(caramello);
CandyBar what = new CandyBar("Whatchamacallit", CandyBar.Color.YELLOW, 1.6);
list.add(what);
CandyBar almond = new CandyBar("Almond Joy", CandyBar.Color.BLUE, 1.61);
list.add(almond);
CandyBar goodbar = new CandyBar("Mr. Goodbar", CandyBar.Color.YELLOW, 1.75);
list.add(goodbar);
CandyBar twix = new CandyBar("Twix", CandyBar.Color.GOLD, 1.79);
list.add(twix);
CandyBar henry = new CandyBar("Oh Henry", CandyBar.Color.YELLOW, 1.8);
list.add(henry);
CandyBar milkyWay = new CandyBar("Milky Way", CandyBar.Color.GREEN, 1.84);
list.add(milkyWay);
CandyBar payDay = new CandyBar("PayDay", CandyBar.Color.ORANGE, 1.85);
list.add(payDay);
CandyBar snickers = new CandyBar("Snickers", CandyBar.Color.BLUE, 1.86);
list.add(snickers);
CandyBar butterfinger = new CandyBar("Butterfinger", CandyBar.Color.YELLOW, 1.9);
list.add(butterfinger);
CandyBar musketeers = new CandyBar("Three Musketeers", CandyBar.Color.SILVER, 1.92);
list.add(musketeers);
CandyBar reeses = new CandyBar("Reese's FastBreak", CandyBar.Color.ORANGE, 2);
list.add(reeses);
CandyBar babyRuth = new CandyBar("Baby Ruth", CandyBar.Color.SILVER, 2.1);
list.add(babyRuth);
}
}
The printInfo() method is declared on the CandyBar object, but here you are trying to call printInfo() on a String object. This method does not exist on String.
/**
* This method searches a list to find a candy bar by name.
*
* #param list the list to search
* #param n a name to find
* #return the index of the candy bar
*/
public static int findCandyBar(ArrayList<CandyBar> list, String n)
{
for(int i = 0; i < list.size(); i++){
if(list.get(i).getName() == n){
return n.printInfo(i); <-- calling n.printInfo(i) will not work as printInfo() does not exist on String
You instead need to pay attention to the method signature of printInfo():
It exists on CandyBar, not on String.
It does not accept any parameter arguments.
It is a void method, i.e. does not return an object.
So instead of:
return n.printInfo(i);
Use this:
i.printInfo();
I am Looking for some insight on how to make my card game know when the decks I have created have run out of cards.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CardDealer {
public static void main(String[] args) {
System.out.println("Welcome to Shuffle!");
Scanner console = new Scanner(System.in);
Map<Integer, Deck> decks = new HashMap<Integer, Deck>();
int deckNum = getNumberOfDecks(console);
int cardNum = getNumberOfCards(console);
String readString = console.nextLine();
while(readString!=null)
{
System.out.println(readString);
if(readString.equals(""))
for(int i = 0; i < deckNum; i++){
decks.put(i, new Deck(cardNum));
}
for(int key : decks.keySet()){
System.out.println("Deck # "+ key + " " +decks.get(key).toString());
if(key >= 52)
key = key + cardNum;
else if(key == 51)
System.out.println("All GONE!");
}
if(console.hasNextLine())
readString = console.nextLine();
else
readString = null;
}
}
/**
* Get number of decks
* #param console
* #return
*/
public static int getNumberOfDecks(Scanner console){
int tempNumDecks = 0;
boolean isOk = false;
System.out.println("How many decks would you like to use?");
do{
try{
String userInput = console.nextLine();
tempNumDecks = Integer.parseInt(userInput);
} catch(Exception e){
System.out.println ("Invalid input. Enter a number > 0");
System.out.println("Enter an integer greater than 0:");
}
isOk = true;
}while(isOk == false);
return tempNumDecks;
}
/**
* Get number of cards
* #param console
* #return
*/
public static int getNumberOfCards(Scanner console){
int tempNumCards = 0;
boolean isOk = false;
System.out.println("How many cards would you like to deal?");
do{
try{
String userInput = console.nextLine();
tempNumCards = Integer.parseInt(userInput);
if(tempNumCards <= 0) {
System.out.println ("Invalid input. Enter a number > 0");
} else{
isOk = true;
}//end else
}//end try
catch(Exception e){
System.out.println("Enter an integer greater than 0:");
}//end catch
}while(isOk == false);
return tempNumCards;
}//end getNumberOfCards()
}
Deck class:
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
public class Deck {
/** Cards instance **/
private List<Card> cards;
/** Random generator **/
private Random r;
public Deck(int numberOfCards)
{
cards = new ArrayList<Card>(numberOfCards);
int tempCardIndex = 0;
for (int a=0; a<=3; a++)
{
for (int b=0; b<=12; b++)
{
cards.add( new Card(a,b) );
}
}
/** Shuffle this deck **/
shuffle(cards);
/** Slice the deck by our number of cards **/
cards = cards.subList(0, numberOfCards);
}
/**
* Shuffle a list
* #param list
*/
public void shuffle(List<Card> list) {
if (r == null) {
r = new Random();
}
shuffle(list, r);
}
/**
* Shuffle a list with Random rnd
* #param list
* #param rnd
*/
public void shuffle(List<Card> list, Random rnd) {
int size = list.size();
Object[] arr = list.toArray();
// Shuffle array
for (int i=size; i>1; i--)
swap(arr, i-1, rnd.nextInt(i));
// Dump array back into list
ListIterator<Card> it = list.listIterator();
for (int i=0; i<arr.length; i++) {
it.next();
it.set((Card) arr[i]);
}
}
/**
* Swap elements in List
* #param list
* #param i
* #param j
*/
public void swap(List<Card> list, int i, int j) {
final List l = list;
l.set(i, l.set(j, l.get(i)));
}
/**
* Swap Elements in Array
* #param arr
* #param i
* #param j
*/
private static void swap(Object[] arr, int i, int j) {
Object tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* Draw a card
* #return
*/
public Card drawFromDeck()
{
return cards.remove(0);
}
/** Get total Cards
*
* #return cards size
*/
public int getTotalCards()
{
return cards.size();
}
/**
* to String override
*/
public String toString(){
return cards.toString();
}
}
Card Class:
public class Card
{
private int rank, suit;
private final String[] suits = { "hearts", "spades", "diamonds", "clubs" };
private final String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
public Card(int suit, int rank)
{
this.rank=rank;
this.suit=suit;
}
public #Override String toString()
{
return ranks[rank] + " of " + suits[suit];
}
public int getRank() {
return rank;
}
public int getSuit() {
return suit;
}
}
So this prints a hashmap of the user specified amount of cards in a user specified amount of decks.
Like so:
Deck # 0 [Jack of hearts, 3 of spades, 7 of spades, 6 of hearts]
Deck # 1 [6 of hearts, 9 of clubs, King of spades, 2 of clubs]
Deck # 2 [5 of spades, King of clubs, Queen of clubs, King of spades]
Deck # 3 [5 of spades, 6 of hearts, 9 of clubs, 5 of diamonds]
It does this every time the user presses enter. My problem is, I want it to stop allowing the user to draw more cards from the deck(s) when all of the cards from each of the decks runs out. Is this possible? I have been told by a colleague to use a boolean somehow to make this work but I'm stumped.
Thanks for the help guys.
You could simply call the method that checks the number of cards, getTotalCards() before calling drawFromDeck(). Then if it's 0, you know that no cards are left.
Note that with such questions, it's always best to show us your attempt to solve it as part of your question, else you're just cheating yourself out of a learning opportunity, and preventing us from seeing what may be wrong with your logic.
I could really use your help!
I fixed most of the errors but im stuck on this one at the moment.
Sorry for the long code and please let me know if you see any additional errors or mistakes i might have missed. I really appreciate your help <3
I keep receiving this Error and I cant seem to figure out why:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at mypokergame1.MyPokerGame.play(MyPokerGame.java:338)
my Card class:
import java.util.*;
import java.util.Scanner;
/** class PlayingCardException: It is used for errors related to Card and Deck objects
* Do not modify this class!
*/
class PlayingCardException extends Exception {
/* Constructor to create a PlayingCardException object */
PlayingCardException (){
super ();
}
PlayingCardException ( String reason ){
super ( reason );
}
}
/** class Card : for creating playing card objects
* it is an immutable class.
* Rank - valid values are 1 to 13
* Suit - valid values are 0 to 3
* Do not modify this class!
*/
class Card {
/* constant suits and ranks */
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
/* Data field of a card: rank and suit */
private int cardRank; /* values: 1-13 (see Rank[] above) */
private int cardSuit; /* values: 0-3 (see Suit[] above) */
/* Constructor to create a card */
/* throw PlayingCardException if rank or suit is invalid */
public Card(int rank, int suit) throws PlayingCardException {
if ((rank < 1) || (rank > 13))
throw new PlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new PlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
/* Accessor and toString */
/* You may impelemnt equals(), but it will not be used */
public int getRank() { return cardRank; }
public int getSuit() { return cardSuit; }
public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }
/* Few quick tests here */
public static void main(String args[])
{
try {
Card c1 = new Card(1,3); // A Spades
System.out.println(c1);
c1 = new Card(10,0); // 10 Clubs
System.out.println(c1);
c1 = new Card(10,5); // generate exception here
}
catch (PlayingCardException e)
{
System.out.println("PlayingCardException: "+e.getMessage());
}
}
}
/** class Decks represents : n decks of 52 playing cards
* Use class Card to construct n * 52 playing cards!
*
* Do not add new data fields!
* Do not modify any methods
* You may add private methods
*/
class Decks {
/* this is used to keep track of original n*52 cards */
private List<Card> originalDecks;
/* this starts with n*52 cards deck from original deck */
/* it is used to keep track of remaining cards to deal */
/* see reset(): it resets dealDecks to a full deck */
private List<Card> dealDecks;
/* number of decks in this object */
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
*/
public Decks()
{
// implement this method!
originalDecks = new ArrayList<Card>();
numberDecks=1;
for (int i = 0; i < numberDecks; i++) {
for (int j = 0; j <= 3; j++) {
for (int k = 1; k <= 13; k++) {
try {
originalDecks.add(new Card(k, j));
} catch (PlayingCardException e) {
System.out.println("PlayingCardException: " + e.getMessage());
}
}
}
}
dealDecks = new ArrayList<Card>(originalDecks);
}
/**
* Constructor: Creates n decks (52 cards each deck) of playing cards in
* originalDecks and copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
*/
public Decks(int n)
{
// implement this method!
originalDecks = new ArrayList<Card>();
numberDecks = n;
for (int i = 0; i < numberDecks; i++) {
for (int j = 0; j <= 3; j++) {
for (int k = 1; k <= 13; k++) {
try {
originalDecks.add(new Card(k, j));
} catch (PlayingCardException e) {
System.out.println("PlayingCardException: " + e.getMessage());
}
}
}
}
dealDecks = new ArrayList<Card>(originalDecks);
}
/**
* Task: Shuffles cards in deal deck.
* Hint: Look at java.util.Collections
*/
public void shuffle()
{
// implement this method!
java.util.Collections.shuffle(dealDecks);
}
/**
* Task: Deals cards from the deal deck.
*
* #param numberCards number of cards to deal
* #return a list containing cards that were dealt
* #throw PlayingCardException if numberCard > number of remaining cards
*
* Note: You need to create ArrayList to stored dealt cards
* and should removed dealt cards from dealDecks
*
*/
public List<Card> deal(int numberCards) throws PlayingCardException
{
// implement this method!
List dealtCards = new ArrayList<Card>();
if (numberCards > dealDecks.size()) {
throw new PlayingCardException("Not enough cards to deal");
}
for (int i = 0; i < numberCards; i++) {
dealtCards.add(dealDecks.remove(0));
}
return dealtCards;
}
/**
* Task: Resets deal deck by getting all cards from the original deck.
*/
public void reset()
{
// implement this method!
dealDecks = new ArrayList<Card>();
for(Card card : originalDecks) {
dealDecks.add(card);
}
}
/**
* Task: Return number of remaining cards in deal deck.
*/
public int remain()
{
return dealDecks.size();
}
/**
* Task: Returns a string representing cards in the deal deck
*/
public String toString()
{
return ""+dealDecks;
}
/* Quick test */
/* */
/* Do not modify these tests */
/* Generate 2 decks of cards */
/* Loop 2 times: */
/* Deal 30 cards for 4 times */
/* Expect exception last time */
/* reset() */
public static void main(String args[]) {
System.out.println("******* Create 2 decks of cards *********\n\n");
Decks decks = new Decks(2);
for (int j=0; j < 2; j++)
{
System.out.println("\n************************************************\n");
System.out.println("Loop # " + j + "\n");
System.out.println("Before shuffle:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
System.out.println("\n==============================================\n");
int numHands = 4;
int cardsPerHand = 30;
for (int i=0; i < numHands; i++)
{
decks.shuffle();
System.out.println("After shuffle:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
try {
System.out.println("\n\nHand "+i+":"+cardsPerHand+" cards");
System.out.println("\n\t"+decks.deal(cardsPerHand));
System.out.println("\n\nRemain:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
System.out.println("\n==============================================\n");
}
catch (PlayingCardException e)
{
System.out.println("*** In catch block : PlayingCardException : msg : "+e.getMessage());
}
}
decks.reset();
}
}
}
my Card Class:
package mypokergame1;
import java.util.*;
import java.util.Scanner;
/** class PlayingCardException: It is used for errors related to Card and Deck objects
* Do not modify this class!
*/
class PlayingCardException extends Exception {
/* Constructor to create a PlayingCardException object */
PlayingCardException (){
super ();
}
PlayingCardException ( String reason ){
super ( reason );
}
}
/** class Card : for creating playing card objects
* it is an immutable class.
* Rank - valid values are 1 to 13
* Suit - valid values are 0 to 3
* Do not modify this class!
*/
class Card {
/* constant suits and ranks */
static final String[] Suit = {"Clubs", "Diamonds", "Hearts", "Spades" };
static final String[] Rank = {"","A","2","3","4","5","6","7","8","9","10","J","Q","K"};
/* Data field of a card: rank and suit */
private int cardRank; /* values: 1-13 (see Rank[] above) */
private int cardSuit; /* values: 0-3 (see Suit[] above) */
/* Constructor to create a card */
/* throw PlayingCardException if rank or suit is invalid */
public Card(int rank, int suit) throws PlayingCardException {
if ((rank < 1) || (rank > 13))
throw new PlayingCardException("Invalid rank:"+rank);
else
cardRank = rank;
if ((suit < 0) || (suit > 3))
throw new PlayingCardException("Invalid suit:"+suit);
else
cardSuit = suit;
}
/* Accessor and toString */
/* You may impelemnt equals(), but it will not be used */
public int getRank() { return cardRank; }
public int getSuit() { return cardSuit; }
public String toString() { return Rank[cardRank] + " " + Suit[cardSuit]; }
/* Few quick tests here */
public static void main(String args[])
{
try {
Card c1 = new Card(1,3); // A Spades
System.out.println(c1);
c1 = new Card(10,0); // 10 Clubs
System.out.println(c1);
c1 = new Card(10,5); // generate exception here
}
catch (PlayingCardException e)
{
System.out.println("PlayingCardException: "+e.getMessage());
}
}
}
/** class Decks represents : n decks of 52 playing cards
* Use class Card to construct n * 52 playing cards!
*
* Do not add new data fields!
* Do not modify any methods
* You may add private methods
*/
class Decks {
/* this is used to keep track of original n*52 cards */
private List<Card> originalDecks;
/* this starts with n*52 cards deck from original deck */
/* it is used to keep track of remaining cards to deal */
/* see reset(): it resets dealDecks to a full deck */
private List<Card> dealDecks;
/* number of decks in this object */
private int numberDecks;
/**
* Constructor: Creates default one deck of 52 playing cards in originalDecks and
* copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
*/
public Decks()
{
// implement this method!
originalDecks = new ArrayList<Card>();
numberDecks=1;
for (int i = 0; i < numberDecks; i++) {
for (int j = 0; j <= 3; j++) {
for (int k = 1; k <= 13; k++) {
try {
originalDecks.add(new Card(k, j));
} catch (PlayingCardException e) {
System.out.println("PlayingCardException: " + e.getMessage());
}
}
}
}
dealDecks = new ArrayList<Card>(originalDecks);
}
/**
* Constructor: Creates n decks (52 cards each deck) of playing cards in
* originalDecks and copy them to dealDecks.
* initialize numberDecks=n
* Note: You need to catch PlayingCardException from Card constructor
* Use ArrayList for both originalDecks & dealDecks
*/
public Decks(int n)
{
// implement this method!
originalDecks = new ArrayList<Card>();
numberDecks = n;
for (int i = 0; i < numberDecks; i++) {
for (int j = 0; j <= 3; j++) {
for (int k = 1; k <= 13; k++) {
try {
originalDecks.add(new Card(k, j));
} catch (PlayingCardException e) {
System.out.println("PlayingCardException: " + e.getMessage());
}
}
}
}
dealDecks = new ArrayList<Card>(originalDecks);
}
/**
* Task: Shuffles cards in deal deck.
* Hint: Look at java.util.Collections
*/
public void shuffle()
{
// implement this method!
java.util.Collections.shuffle(dealDecks);
}
/**
* Task: Deals cards from the deal deck.
*
* #param numberCards number of cards to deal
* #return a list containing cards that were dealt
* #throw PlayingCardException if numberCard > number of remaining cards
*
* Note: You need to create ArrayList to stored dealt cards
* and should removed dealt cards from dealDecks
*
*/
public List<Card> deal(int numberCards) throws PlayingCardException
{
// implement this method!
List dealtCards = new ArrayList<Card>();
if (numberCards > dealDecks.size()) {
throw new PlayingCardException("Not enough cards to deal");
}
for (int i = 0; i < numberCards; i++) {
dealtCards.add(dealDecks.remove(0));
}
return dealtCards;
}
/**
* Task: Resets deal deck by getting all cards from the original deck.
*/
public void reset()
{
// implement this method!
dealDecks = new ArrayList<Card>();
for(Card card : originalDecks) {
dealDecks.add(card);
}
}
/**
* Task: Return number of remaining cards in deal deck.
*/
public int remain()
{
return dealDecks.size();
}
/**
* Task: Returns a string representing cards in the deal deck
*/
public String toString()
{
return ""+dealDecks;
}
/* Quick test */
/* */
/* Do not modify these tests */
/* Generate 2 decks of cards */
/* Loop 2 times: */
/* Deal 30 cards for 4 times */
/* Expect exception last time */
/* reset() */
public static void main(String args[]) {
System.out.println("******* Create 2 decks of cards *********\n\n");
Decks decks = new Decks(2);
for (int j=0; j < 2; j++)
{
System.out.println("\n************************************************\n");
System.out.println("Loop # " + j + "\n");
System.out.println("Before shuffle:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
System.out.println("\n==============================================\n");
int numHands = 4;
int cardsPerHand = 30;
for (int i=0; i < numHands; i++)
{
decks.shuffle();
System.out.println("After shuffle:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
try {
System.out.println("\n\nHand "+i+":"+cardsPerHand+" cards");
System.out.println("\n\t"+decks.deal(cardsPerHand));
System.out.println("\n\nRemain:"+decks.remain()+" cards");
System.out.println("\n\t"+decks);
System.out.println("\n==============================================\n");
}
catch (PlayingCardException e)
{
System.out.println("*** In catch block : PlayingCardException : msg : "+e.getMessage());
}
}
decks.reset();
}
}
}
The exception you have received is quite informative... learning to read exceptions and trace them is an important process!
It looks to me as if at line 338 of MyPokerGame.java you are calling scanner.nextLine without first double-checking that scanner.hasNextLine()
calling nextLine() when the scanner doesn't have a next line will throw this exception.
the idiomatic way to use the Scanner class is:
while(scanner.hasNextLine()){
str=scanner.nextLine();
//...
}
If you ever get an exception check the source of the exception and refer to the docs for the Exception type (or just paste the execption into google and you'll probably find a link to the answer right here on StackOVerflow!)
I'm new to java and I'm becoming overwhelmed by the assignment my professor gave us because I don't really understand how to use the classes and methods that he predesignated for the assignment.
What do I need to provide in the method main in order to use the method:
public static void printHand(Card[] hand)
where Card is a the name of a separate class? If anyone could give me a quick explanation of this question, I would be very grateful.
This is the Card class if it is any help for answering the question:
public class Card {
// Constants for representing the suits
public final static int CLUBS = 0;
public final static int HEARTS = 1;
public final static int SPADES = 2;
public final static int DIAMONDS = 3;
// Constants for representing values of
// ace, jack, queen, and king.
public final static int ACE = 1;
public final static int JACK = 11;
public final static int QUEEN = 12;
public final static int KING = 13;
// Final will keep them from being changed
// after cards are constructed.
private final int value;
private final int suit;
/**
* Constructs a card with a specified suit and value.
*
* #param value
* the value of the card. 2 through 10 are used to specify the
* cards with those corresponding values, and constants exist for
* specifying ace, jack, queen, and king
* #param suit
* the suit of the card. Use one of Card.CLUBS, Card.Hearts,
* Card.SPADES, or Card.DIAMONDS
*/
public Card(int value, int suit) {
if (value < ACE || value > KING) {
throw new IllegalArgumentException("Illegal card value: " + value);
}
if (suit < CLUBS || suit > DIAMONDS) {
throw new IllegalArgumentException("Illegal card suit: " + suit);
}
this.value = value;
this.suit = suit;
}
/**
* Constructs a new card with the same value and suit as the original.
* #param original the card to be copied
*/
public Card(Card original) {
this(original.value, original.suit);
}
/**
* Gets this card's suit.
*
* #return the suit of this card
*/
public int getSuit() {
return suit;
}
/**
* Gets this card's value
*
* #return the value of this card
*/
public int getValue() {
return value;
}
/**
* Gets a letter representing the suit
*
* #return a single letter, either "C", "H", "S", or "D", representing
* clubs, hearts, spades, and diamonds respectively
*/
private String getSuitString() {
return "" + "CHSD".charAt(suit);
}
/**
* Gets a one- or two-character string representing the value
*
* #return either "2" through "10" or "A", "J", "Q", or "K"
*/
private String getValueString() {
return "A 2 3 4 5 6 7 8 9 10J Q K ".substring(2 * (value - 1), 2 * value).trim();
}
/**
* Returns whether two cards have the same suit and value
*
* #param other
* the other object to be compared
* #return true if the other object is a card with the same suit and value
* as this card
*/
public boolean equals(Object other) {
if (!(other instanceof Card))
return false;
if (this == other) {
return true;
}
Card that = (Card) other;
return this.suit == that.suit && this.value == that.value;
}
/**
* Returns a String representation of this card, by combining its value and
* suit (see getValueString() and getSuitString)
*
* #return a 2- or 3-character representation of this card (such as "JD" for
* the jack of diamonds, or "10H" for the 10 of hearts
*/
public String toString() {
return getValueString() + getSuitString();
}
}
You use the toString method in the Card class wich returns a String
System.out.println(card.toString);
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Card[] myHand = new Card[3];
//King of Spades
myHand[0] = new Card(Card.KING, Card.SPADES);
//Ace of spades
myHand[1] = new Card(Card.ACE, Card.SPADES);
//two of hearts
myHand[2] = new Card(2, Card.HEARTS);
printHand(myHand);
}
public static void printHand(Card[] hand) {
System.out.println("The hand concists of the following cards");
for(Card card : hand) {
System.out.println(card.toString());
}
}
}
First you have to create an array of Cards (Card[]) in the main method or any static method will do, because only static methods can be called in other static methods.
Then you can pass that array of cards to the printHand() method, which in-turn, should print out each card that was added to the array of cards. Make sure to populate your array of cards with instances of the Card object.
public static void printHand(Card[] hand) {
for (Card card : hand) {
System.out.println(card);
}
}
public static void main(String[] args) {
Card[] cards = {
new Card(Card.ACE, Card.HEARTS),
new Card(Card.KING, Card.HEARTS),
new Card(Card.QUEEN, Card.HEARTS),
new Card(Card.JACK, Card.HEARTS),
new Card(Card.QUEEN, Card.SPADES)
};
printHand(cards);
}
Output:
AH
KH
QH
JH
QS
This is an assignment for class that involves creating a hotel guest service. I created the 2d array below with 8 "floors", 20 "rooms", and populated them with Room objects. I am currently trying to use nested for-loops to go through each Room object and assign it a room number. For example, floor 1 would contain rooms 101-120.
The class below is a test class that I am using.
public class Test {
public Test() {
}
public static void main(String[] args) {
/**
* Creates a two dimensional array with 8 rows and 20 columns
*/
Room [][] hotelBuild = new Room[8][20];
/**
* populates the 2d array with Room objects
*/
for (int floor=0; floor<hotelBuild.length; floor++) {
for (int room=0; room<hotelBuild[floor].length; room++) {
hotelBuild[floor][room] = new Room();
/**
* used to print out contents of 2d array
*/
//System.out.print(hotelBuild[floor][room]=new Room());
}
}
}
}
Below is class Room that contains the variables, setters, getters, as well as the toString() override method.
public class Room {
//Instance variables
/**
*the rooms number
*/
private int roomNumber;
/** is the room occupied or not
*
*/
private boolean isOccupied;
/** name of guest
*
*/
private String guest;
/** cost per day
*
*/
private double costPerDay;
/** number of days guest is staying
*
*/
int days;
//Constructors
public Room(){
}
/** Construct a room with values above
*
*/
public Room(int room, boolean nonVacant, String guestName, double cost, int day) {
roomNumber = room;
isOccupied = nonVacant;
guest = guestName;
costPerDay = cost;
days = day;
}
// getters
/** gets roomNumber
*
*/
public int getRoomNumber(){
return roomNumber;
}
/** gets isOccupied
*
*/
public boolean getIsOccupied(){
return isOccupied;
}
/** gets guest
*
*/
public String getGuest(){
return guest;
}
/** gets costPerDay
*
*/
public double getCostPerDay(){
return costPerDay;
}
/** gets days
*
*/
public int getDays(){
return days;
}
// setters
/** sets isOccupied
*
*/
public void setIsOccupied(boolean full){
this.isOccupied = full;
}
/** sets days
*
*/
public void setDays(int numDays){
this.days = numDays;
}
/** sets guest name
*
*/
public void setGuest(String name){
this.guest = name;
}
/** formats output depending if room is occupied or not
*
*/
public String toString(){
if(isOccupied == true){
return "Room number: " + roomNumber + "\n"+ "Guest name: "
+ guest + "\n"+ "Cost : " + costPerDay
+ "\n"+ "Days: " + days + "\n";
}
else{
return "Room number " + roomNumber
+ " costs " + costPerDay + "\n";
}
}
}
How do I assign each Room object in the array a unique room number?
You could do
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
Room r = new Room();
r.setRoomNumber(
cleverCalculationWithFloorAndRoomNr(floor, room));
hotelBuild[floor][room]= r;
If you want a way to put the numbers in the correct order then use the varables you alredady have. Use a count for know what floor it is (it will be increased at the end of the first loop). Then room number is Floor * 100 + another variable you reset to 1 at the begining of the first loop. Just a hint to help you. Fill the gaps ;)
int floorNumber = 1;
int roomNumber = 1;
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room();
/**
* used to print out contents of 2d array
*/
//System.out.print(hotelBuild[floor][room]=new Room());
//Add room number here.
//Increase room number
}
//floorNumber increase
//roomNumber reset
}
Once you have achieved this you could try to use the variables you have in the loops (room and floor) with a few minor changes.
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room();
// room number format: xxyy, x = floor, y = room
// this assumes maximum 99 rooms per floor, it should be enough
hotelBuild[floor][room].setNumber((floor + 1) * 100 + room + 1);
}
}
You can pass it through the contructor for example or set with a setter in your class Room (classroom ahahah)
for example:
for (int floor=0; floor<hotelBuild.length; floor++){
for (int room=0; room<hotelBuild[floor].length; room++){
hotelBuild[floor][room]=new Room((floor+1)*100+room+1);
}
}
And in your Room class, you can add a constructor with only the room number as parameter
class Room{
public Room(int roomNumber){
this.roomNumber = roomNumber;
}
...
}