I have almost everything ready for my poker game. What I want to do next is to sort cards in players hand by rank value. You know "two" is byte 2, "three" is byte 3 etc...
This is my enum CardRank class
public enum CardRank {
TWO((byte)2, "Two"),
THREE((byte)3, "Three"),
FOUR((byte)4, "Four"),
FIVE((byte)5, "Five"),
SIX((byte)6, "Six"),
SEVEN((byte)7, "Seven"),
EIGHT((byte)8, "Eight"),
NINE((byte)9, "Nine"),
TEN((byte)10, "Ten"),
JACK((byte)11, "Jack"),
QUEEN((byte)12, "Queen"),
KING((byte)13, "King"),
ACE((byte)14, "Ace");
private final byte rankValue;
private final String rankValueName;
//Constructor
private CardRank(byte rankValue, String rankValueName){
this.rankValue=rankValue;
this.rankValueName = rankValueName;
}
//reusable methods
protected byte getRankValue(){
return rankValue;
}
protected String getRankValueName(){
return rankValueName;
}
}
I need to find a way to sort them using enum values but to be honest I don't really know how.
This method returns enum values of player hand cards:
protected void sortHand(){
for (Hand playerHand: players){
i = 0;
while(i<5){
System.out.println(playerHand.cards.get(i).getRankValue());
i++;
}
}
}
I can't use Collections from a very obvious reason:
The method sort(List) in the type Collections is not applicable for the arguments (Hand)
And this is my Hand class
import java.util.ArrayList;
public class Hand {
protected ArrayList<Card> cards;
private String handCards;
// Constructor
protected Hand() {
cards = new ArrayList<Card>(5);
}
// reusable methods
protected void add(Card card) {
cards.add(card);
}
protected void emptyHand() {
cards.clear();
}
protected void flipHandCards() {
for (Card card : cards) {
card.flipCard();
}
}
protected String displayHand() {
handCards = "";
for (Card i : cards) {
handCards += i.toString() + "\n";
}
return handCards;
}
protected boolean giveCard(Card card, Hand differentHand) {
if (!cards.contains(card)) {
return false;
} else {
cards.remove(card);
differentHand.add(card);
return true;
}
}
}
And this is my Card class
public class Card {
private CardSuit suit;
private CardRank rank;
private String cardName;
private boolean visibility;
//Constructor
protected Card(CardRank rank, CardSuit suit){
this.rank = rank;
this.suit = suit;
}
//reusable methods
protected String getCardSuit(){
return suit.getCardSuit();
}
protected byte getRankValue(){
return rank.getRankValue();
}
protected void flipCard(){
visibility = !visibility;
}
public String toString(){
if (visibility){
cardName="";
cardName+=rank.getRankValueName() + " of " + suit.getCardSuit();
}
else{
cardName = "You cannot see your opponents card";
}
return cardName;
}
}
Help. I appreciate for any help that will direct me into the right direction.
Saying you can't use Guava (Google Collections) for this seems incorrect at face value. Just give hand a sort method that lets it interact with cards (which is an ArrayList).
protected void sortHand(){
for (Hand playerHand: players){
List<Card> sortedHand = playerHand.getSortedCards();
// Do whatever
}
}
Hand.java
public class Hand {
...
public List<Card> getSortedCards() {
Collections.sort(cards);
return cards; // Consider deep copying.
}
}
From there, making Card implement Comparable will let you sort the list.
Card.java
public class Card implements Comparable<Card>
{
...
#Override
public int compareTo(Card o) {
if (this.rank.getRankValue() < o.rank.getRankValue()) {
return -1;
}
else if (o.rank.getRankValue() < this.rank.getRankValue()) {
return 1;
}
return 0;
}
}
protected void sortHand(){
for (Hand playerHand: players){
i = 0;
int []arr = new int[5];
while(i<5){
System.out.println(playerHand.cards.get(i).getRankValue());
arr[i] = playerHand.cards.get(i).getRankValue();
i++;
}
Arrays.sort(arr);
}
}
you can try adding it to an array and call Array.sort(). where i assume that getRankvalue will return an int . try this
ArrayLists can be easily sorted using a Comparator.
You would then get something like this:
cards.sort(new Comparator<Card>() {
#Override
public int compare(Card card1, Card card2) {
// return -1 if card1 should come before card2
// return 0 if card1 and card2 have equal values
// return 1 if card1 should come after card2
}
});
I suggest you use a static array to store cards in hand:
public class Hand {
private static final int MAX_CARD = 5;//modify with your value
protected Card[] cards;
private int currentCardNumber;
private String handCards;
// Constructor
protected Hand() {
cards = new Card[MAX_CARD];
currentCardNumber = 0;
}
// reusable methods
protected void add(Card card) {
if (currentCardNumber == MAX_CARD - 1) { return; }
cards[currentCardNumber] = card;
currentCardNumber++;
}
protected void emptyHand() {
for (int i = 0; i < MAX_CARD; i++) {
cards[i] = null;
}
currentCardNumber = 0;
}
protected void flipHandCards() {
for (int i = 0; i < currentCardNumber; i++) {
cards[i].flipCard();
}
}
protected String displayHand() {
handCards = "";
for (int i = 0; i < currentCardNumber; i++) {
handCards += cards[i].toString() + "\n";
}
return handCards;
}
protected boolean giveCard(Card card, Hand differentHand) {
int index = getCardIndex(card);
if (index == -1) {
return false;
} else {
differentHand.add(remove(index));
return true;
}
}
protected void sortHand() {
for(int i = 0; i < currentCardNumber; i++) {
for(int j = i + 1; j < currentCardNumber; j++) {
if(cards[j].getRankValue() < cards[i].getRankValue()) {
Card tmp = cards[j];
cards[j] = cards[i];
cards[i] = tmp;
}
}
}
}
private int getCardIndex(Card card) {
for (int i = 0; i < currentCardNumber; i++) {
if(card.equals(cards[i]) {
return i;
}
}
return -1;
}
private Card remove(int cardIndex) {
if (currentCardNumber == 0) { return null; }
Card tmp = cards[cardIndex];
for (int i = cardIndex + 1; i < currentCardNumber; i++) {
cards[i - 1] = cards[i];
}
cards[currentCardNumber - 1] = null;
currentCardNumber--;
return tmp;
}
}
Or you can create your own List and apply a your own sort method.
Related
I am sort of new to coding, and I have a coding assignment that helps us practice with constructors and classes. I feel that I am well versed for my level, so I came here posting this because I was stumped. I get an error in Main when trying to do print getColleges(20)), a method inside CollegeGroup. CollegeGroup is supposed to be an array of College objects. Colleges 20 is supposed to sort colleges under a tuition of $20,000. However I get the error
cannot find symbol
symbol: method getColleges(int)
location: class Main
What do I change so i can correctly print getColleges(20))? Thank you for your help
College.java
package colleges;
public class College {
private int tuition;
private String name;
private String region;
private double minGPA;
public College(int aTuition, String aName, String aRegion, double minScore) {
tuition = aTuition;
name = aName;
region = aRegion;
minGPA = minScore;
}
public double getMinimumGPA() {
return minGPA;
}
public String getName() {
return name;
}
public int getTuition() {
return tuition;
}
public String getRegion() {
return region;
}
public void setTuition(int aTuition) {
tuition = aTuition;
}
public String toString() {
return ("College: " + name + "\tTuition: " + tuition
+ "\tRegion: " + region);
}
CollegeGroup.java
package colleges;
import java.util.List;
import java.util.ArrayList;
public class CollegeGroup {
private List<College> colleges = new ArrayList<College>();
public void addCollege(College aCollege) {
colleges.add(aCollege);
}
public void removeCollege(String collegeName) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getName().equalsIgnoreCase(collegeName)) {
colleges.remove(i);
}
}
}
public void updateTuition(String collegeName, int newTuition) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getName().equalsIgnoreCase(collegeName)) {
colleges.get(i).setTuition(newTuition);
}
}
}
public List<College> getColleges() {
return colleges;
}
public List<College> getColleges(String region) {
//return a list of colleges in the given region
List<College> regionCollege = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getRegion().equalsIgnoreCase(region)) {
regionCollege.add(colleges.get(i));
}
}
return regionCollege;
}
public List<College> getColleges(int maxTuition) {
//return a list of colleges with tuition below maxTuition
List<College> mTut = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < maxTuition) {
mTut.add(colleges.get(i));
}
}
return mTut;
}
public List<College> getColleges(double myGPA, int maxTuition) {
//return a list of colleges with minimum GPA requirements below
//myGPA, and tuitions below maxTuition
List<College> perfCollege = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < maxTuition && colleges.get(i).getMinimumGPA() <= myGPA) {
perfCollege.add(colleges.get(i));
}
}
return perfCollege;
}
public void sortCollegesByRegion() {
//sort in the following order:
//Northeast, Southeast, MidWest, West
List<College> Northeast = new ArrayList<College>();
List<College> Southeast = new ArrayList<College>();
List<College> MidWest = new ArrayList<College>();
List<College> West = new ArrayList<College>();
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getRegion().equalsIgnoreCase("Northeast")) {
Northeast.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("Southeast")) {
Southeast.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("MidWest")) {
MidWest.add(colleges.get(i));
} else if (colleges.get(i).getRegion().equalsIgnoreCase("West")) {
West.add(colleges.get(i));
}
}
}
public void sortCollegesByMinimumGPA() {
//code goes here, sort from low to high.
int smallest = Integer.MAX_VALUE;
List<College> sorted = new ArrayList<College>();
while (colleges.size() != 0) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getMinimumGPA() < smallest) {
sorted.add(colleges.get(i));
colleges.remove(i);
}
}
}
sorted = colleges;
}
public void sortCollegesByTuition() {
//code goes here, sort from low to high.
int smallest = Integer.MAX_VALUE;
List<College> sorted = new ArrayList<College>();
while (colleges.size() != 0) {
for (int i = 0; i < colleges.size(); i++) {
if (colleges.get(i).getTuition() < smallest) {
sorted.add(colleges.get(i));
colleges.remove(i);
}
}
}
sorted = colleges;
}
public String toString() {
String out = "";
for (int i = 0; i < colleges.size(); i++) {
out += colleges.get(i).toString(); //test whether toString is necessary on colleges.get()
out += "\n";
}
return out.substring(0, out.length() - 1);
}
Main.java
package colleges;
public class Main {
public static void main(String[] args) {
CollegeGroup collegeList = new CollegeGroup();
College colUni = new College(17025,"College University", "Northeast", 2.3);
College westCol = new College(28450,"Westcoast College", "West", 2.9);
College budgCol = new College(700,"Budget College", "Southeast", 1.0);
College goodUni = new College(95000,"Reallygood University", "Northeast", 3.9);
College partyUni = new College(22150,"Partyschool U ", "West", 2.1);
College hogwarts = new College(12000,"Hogwarts", "Northeast", 3.5);
collegeList.addCollege(colUni);
collegeList.addCollege(westCol);
collegeList.addCollege(budgCol);
collegeList.addCollege(goodUni);
collegeList.addCollege(partyUni);
collegeList.addCollege(hogwarts);
System.out.println(collegeList.getColleges());
System.out.println(colUni.toString());
budgCol.setTuition(8);
System.out.println(getColleges(20));
}
I have tried again and again but the loop is stuck at the king of clubs.
currently I am trying to generate a deck of cards and print it out to check if the deck is actual
import java.util.*;
import java.math.*;
public class Deck extends Card{
private static Card[][]cardDeck=new Card[4][13];
int counter;
public Deck (String suit, String cardType, int value)
{
super(suit,cardType,value);
}
public void removeCard()
{
if(counter>=40)
generateDeck();
int Randr=(int)(Math.random()*26);
int Randc=(int)(Math.random()*2);
if(cardDeck[Randr][Randc]==null)
{
removeCard();
}
else
{
cardDeck[Randr][Randc]=null;
counter++;
}
}
public void print2DArray()
{
for(int i=0;i<cardDeck.length;i++)
{
for(int j=0;j<cardDeck[0].length;j++)
{
System.out.print(super.draw(cardDeck[i][j])+" "+j);
}
System.out.println();
}
}
public static void generateDeck()
{
for(int i=0; i<cardDeck.length;i++) {
for(int j=0;j<cardDeck[0].length;j++) {
if(i==0)
{
if(j==0)
{
cardDeck[0][0]=new Card("Clubs","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Clubs",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Clubs","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Clubs","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Clubs","King",10);
continue;
}
else if(i==1)
{
if(j==0)
{
cardDeck[1][0]=new Card("Hearts","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Hearts",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Hearts","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Hearts","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Hearts","King",10);
continue;
}
}
else if(i==2)
{
if(j==0)
{
cardDeck[2][0]=new Card("Spades","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Spades",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Spades","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Spades","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Spades","King",10);
continue;
}
}
else if(i==3)
{
if(j==0)
{
cardDeck[3][0]=new Card("Diamonds","Ace",1);
continue;
}
else if(j>0&&j<10)
{
cardDeck[i][j]=new Card("Diamonds",""+(j+1),j+1);
continue;
}
else if(j==10)
{
cardDeck[i][j]=new Card("Diamonds","Jack",10);
continue;
}
else if(j==11)
{
cardDeck[i][j]=new Card("Diamonds","Queen",10);
continue;
}
else if(j==12)
{
cardDeck[i][j]=new Card("Diamonds","King",10);
continue;
}
}
}
}
}
}
}
my card class is just a basic class with a few get methods
public class Card {
private static String suit;
private static int numVal;
private static String cardType;
public Card(String s,String cT, int val) {
suit=s;
numVal=val;
cardType=cT;
}
public String draw(Card card) {
return "Your card is "+card.getSuit()+" "+card.getCardType()+" its value is "+card.getValue();
}
public static String getSuit()
{
return suit;
}
public static String getCardType()
{
return cardType;
}
public static int getValue()
{
return numVal;
}
}
my main method is just to check if it will print
public class TestEnvironment {
public static void main(String[] args) {
Deck x= new Deck("","",0);
x.generateDeck();
x.print2DArray();
}
}
heres my updated code for the if else statements aforementioned
import java.util.*;
import java.math.*;
public class Deck extends Card{
private static Card[][]cardDeck=new Card[4][13];
int counter;
public Deck (String suit, String cardType, int value)
{
super(suit,cardType,value);
}
public void removeCard()
{
if(counter>=40)
generateDeck();
int Randr=(int)(Math.random()*26);
int Randc=(int)(Math.random()*2);
if(cardDeck[Randr][Randc]==null)
{
removeCard();
}
else
{
cardDeck[Randr][Randc]=null;
counter++;
}
}
public void print2DArray()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<cardDeck[0].length;j++)
{
System.out.print(i);
//System.out.println(super.draw(cardDeck[i][j])+" "+i+","+j);
}
System.out.println();
}
}
public static void generateDeck()
{ int value=0;
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};
for (int i=0;i<suits.length;i++)
for (int j=0;j<ranks.length;j++)
{
cardDeck[i][j] = new Card(suits[i],ranks[j],value);
if(j>9)
value =10;
else
value=j+1;
cardDeck[i][j] = new Card(suits[i],ranks[j],value);
}
Don't use a 2D Array. Instead use an ArrayList to hold the cards.
Then you create two loops to add the cards to the ArrayList. The outer loop will iterate through the 4 suits and the inner loop will add the 13 cards for each suit.
Then you can use Collections.shuffle() to shuffle the Cards in the ArrayList.
To play a card you just remove card 0 from the ArrayList.
Edit:
but the loop is stuck at the king of clubs.
Well your generateCards() method uses too many if/else statements to generate the cards. It is hard to notice which if/else statement might be causing the problem.
You can simplify the code by using arrays and loops.
Something like:
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace", "2", "3", ... , "Jack", "Queen", "King"};
for (each suit) // assume i is the index
for (each rank) // assume j is the index
{
int value = (j < 10) ? 10 : j;
cardDeck[i][j] = new Card(...);
}
}
Edit 2:
it is stuck at the spades of kings
I'm guessing the following is your problem:
private static String suit;
private static int numVal;
private static String cardType;
Don't use static variables. The Static keyword means that all instances of the Card class will share the same value.
I'm working on a program which should instantiate n amount of threads. Their job is to draw from a deck existing of 52 distinct cards, wait until the round have been evaluated(who had the highest card) and the user has the highest card shown and then repeat until the deck is empty.
The first round runs flawless, not accounting for the wrong evaluation of the cards, but then the program just locks. Never drawing new cards.
I can't quite figure out what the problem is, but my guess is that I'm calling notifyAll() before the threads wake, causing a deadlock. Even though I'm counting the number of waiting threads and only notifying if the number of waiting threads corresponds to the number of players.
EDIT: I found out that if I debug, the code runs smoothly and as intended. But as soon as I run it, it runs as earlier described.
public class Deck {
Stack<Card> stack = new Stack<>();
public Deck()
{
makeAndShuffleDeck();
}
public synchronized Card drawOneCard()
{
Card card = stack.pop();
System.out.println(Thread.currentThread() + " is drawing " + card);
return card;
}
public void setCardValues(int x)
{
if(x == 0)
{
Rank.ACE.setValue(14);
}
else
{
Rank.ACE.setValue(1);
}
}
public void makeAndShuffleDeck()
{
for(Suit suit : Suit.values())
{
for(Rank value : Rank.values())
{
stack.add(new Card(suit,value));
}
}
Collections.shuffle(stack);
}
public Stack<Card> getDeck()
{
return stack;
}
}
public class Round {
ArrayList<Thread> playersInTheRound = new ArrayList<>();
ArrayList<Card> cardsDrawnInTheRound = new ArrayList<>();
Deck deck;
int numberOfRounds;
public Round(int nrOfPlayers, Deck deck)
{
this.deck = deck;
fillListWithPlayers(nrOfPlayers);
calcNumberOfRounds();
for(Thread p: playersInTheRound)
{
p.start();
}
}
public void fillListWithPlayers(int nrOfPlayers)
{
for (int i = 0; i < nrOfPlayers; i++)
{
playersInTheRound.add(new Thread(new Player(deck, this)));
}
}
public void addPlayerCards(Card card)
{
cardsDrawnInTheRound.add(card);
}
public void calcNumberOfRounds()
{
numberOfRounds = deck.getDeck().size()/playersInTheRound.size();
}
public void playRound()
{
while(numberOfRounds > 0)
{
findWinnerOfRound();
cardsDrawnInTheRound.clear();
while(Player.waiting == playersInTheRound.size())
{
synchronized (this)
{
this.notifyAll();
}
Player.waiting = 0;
}
numberOfRounds--;
}
}
public void findWinnerOfRound()
{
Card highestCard = null;
Comparator<Card> comp = (Card c1, Card c2) ->
{
if (c1.rank.getValue() == c2.rank.getValue())
{
if (c1.suit.getRank() > c2.suit.getRank())
{
return 1;
}
return -1;
}
if (c1.rank.getValue() > c2.rank.getValue())
{
return 1;
}
return -1;
};
for (int i = 0; i < cardsDrawnInTheRound.size()-1; i++)
{
for (int j = i+1; j < cardsDrawnInTheRound.size(); j++)
{
if(comp.compare(cardsDrawnInTheRound.get(i), cardsDrawnInTheRound.get(j)) == -1)
{
highestCard = cardsDrawnInTheRound.get(j);
}
highestCard = cardsDrawnInTheRound.get(i);
}
}
System.out.println(cardsDrawnInTheRound);
System.out.println("Winner: " + highestCard);
}
}
public class Player implements Runnable {
Deck deck;
Round round;
public static int waiting = 0;
public Player(Deck deck, Round round)
{
this.deck = deck;
this.round = round;
}
#Override
public void run()
{
Card card = deck.drawOneCard();
synchronized (round)
{
try
{
round.addPlayerCards(card);
waiting++;
round.wait();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
So I rewrote it with your suggestion (Todd Hopp) and updated the post in the (*) section in the BlackJack class so you can see how I have it now but I'm still getting the same errors and it is not printing the computePlayerValue for some reason....
ERROR:
Exception in thread "main" java.lang.NumberFormatException: For input string: "King" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at BlackJack.dealCards(BlackJack.java:25)
at PlayCardGame.main(PlayCardGame.java:9)
P.S. I'm was trying to look this up in the book but couldn't find the answer...The BlackJack class is partially source code from an earlier chapter in the book and I couldn't figure out if it was necessary to have super(); in the constructor there? I thought it only had to do if the parent class constructor had an argument? Any help on if it has to be there and if so what it's doing.
BlackJack Class
public class BlackJack extends CardGameFP{
int computePlayerValue;
int computeDealerValue;
int cardValue;
public BlackJack() {
**super();**
player1 = 2;
player2 = 2;
}
public void display() {
System.out.println("BlackJack");
}
//*************************************************************
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
public void dealCards() {
//Player 1
System.out.println("Player 1:");
for(int x = 0; x < playerHand; x++) {
shuffle();
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit());
}
cardValue1 = getCardValue(fullDeck[0]);
cardValue2 = getCardValue(fullDeck[1]);
computePlayerValue = cardValue1 + cardValue2;
System.out.println(computePlayerValue);
}
//*************************************************************
//Dealer hand
System.out.println("\nPlayer 2:");
for(int x = 0; x < player2; x++) {
System.out.println(fullDeck[x].getRank() + " of " + fullDeck[x].getSuit() );
shuffle();
}
}
}
public class Card {
protected String suit;
protected int value;
protected String rank;
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
public String getRank() {
return rank;
}
public int getValue() {
return value;
}
public String getSuit() {
return suit;
}
public void setSuit(String st) {
suit = st;
}
public void setValue(int val) {
if(val >= LOW_VALUE && val <= HIGH_VALUE) {
value = val;
}
else {
value = LOW_VALUE;
}
if(val == 1) {
rank = "Ace";
}
else if(val == 11) {
rank = "Jack";
}
else if(val == 12) {
rank = "Queen";
}
else if(val == 13) {
rank = "King";
}
else {
rank = Integer.toString(value);
}
}
}
CardGame Class
abstract public class CardGameFP {
int suitNum = 1;
int val = 1;
int player1;
int player2;
protected final int DECK_OF_CARDS = 52;
Card fullDeck[] = new Card[DECK_OF_CARDS];
protected final int LOW_VALUE = 1;
protected final int HIGH_VALUE = 13;
protected final int HIGH_SUIT = 4;
protected final int CARDS_IN_SUIT = 13;
public abstract void display();
public abstract void dealCards();
public CardGameFP() {
for(int i = 0; i < fullDeck.length; i++) {
fullDeck[i] = new Card();
if(suitNum == 1) {
fullDeck[i].setSuit("Spades");
}
else if(suitNum == 2) {
fullDeck[i].setSuit("Hearts");
}
else if(suitNum == 3) {
fullDeck[i].setSuit("Diamonds");
}
else {
fullDeck[i].setSuit("Clubs");
}
fullDeck[i].setValue(val);
val++;
if(val > HIGH_VALUE) {
suitNum++;
val = 1;
}
}//end for
}
public void shuffle() {
for(int firstCard = 0; firstCard < DECK_OF_CARDS; firstCard++ ) {
firstCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
int secondCard = ((int)(Math.random() * 500) % DECK_OF_CARDS);
Card temp = fullDeck[firstCard];
fullDeck[firstCard] = fullDeck[secondCard];
fullDeck[secondCard] = temp;
}
}
}
PlayCardGame Class
PlayerCardGame
public class PlayCardGame {
public static void main(String[] args) {
Card CG = new Card();
BlackJack BJ = new BlackJack();
BJ.display();
BJ.dealCards();
}
}
Instead of this line:
cardValue = Integer.parseInt(fullDeck[0].getRank());
I suggest that you create a getCardValue(Card) method:
public int getCardValue(Card card) {
final String rank = card.getRank();
switch (rank) {
case "Ace":
return 1;
case "King":
case "Queen":
case "Jack":
return 10;
default:
return Integer.parseInt(rank);
}
}
and then use:
cardValue = getCardValue(fullDeck[0]);
EDIT: Following the suggestion by #WorldSEnder, you can define a Rank enum:
public enum Rank {
ACE("Ace", 1),
TWO("2", 2),
...
QUEEN("Queen", 10),
KING("King", 10);
private final String displayName;
private final int value;
protected Rank(String displayName, int value) {
this.displayName = displayName;
this.value = value;
}
public String displayName() {
return displayName;
}
public int value() {
return value;
}
}
Then you can modify Card to use a Rank instead of a String for the rank and use:
cardValue = fullDeck[0].getRank().value();
When you call :
cardValue = Integer.parseInt(fullDeck[0].getRank());
the method Interger.parseInt() is attempting to read an int from a string. The problem is that some cards have ranks which themselves are not strings like, King. So when you return the rank of that card, parseInt() doesn't know how to handle King. You should instead be getting the cards actual value using fullDeck[0].getVaule() and parsing that instead. It will be a string between 1 and 13.
I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}
Your class is abstract. Remove abstract from the class definition.