Trouble printing elements in ArrayList from user input [duplicate] - java

First i have a class called card with this code
public class Card
{
private int value;
private String suit;
// private int value;
//private String rank;
public Card (int v, String s)
{
value=v;
suit=s;
}
public int random()
{
int randomNum = ((int)(Math.random() * 100) % 13 +1);
return randomNum;
}
public void displayCard()
{
System.out.println(value + " of " + suit);
}
}
then i have a class called deck with this code
import java.util.*;
public class Deck
{
public ArrayList<Card> card;
private ArrayList<String> suits;
private ArrayList<Card> hand;
public Deck()// time to build a deck
{
card=new ArrayList<>();
suits=new ArrayList<>();
suits.add("Hearts");
suits.add("Spades");
suits.add("Clubs");
suits.add("Diamonds");
for (int y=2; y<15; y++)
{
card.add(new Card(y,suits.get(0)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(1)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(2)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(3)));
}
}//end of public deck
public ArrayList deal()// deal method
{
hand=new ArrayList<>();
for(int x = 0; x < 5; ++x)//build 5 card hand
{
hand.add(card.get(x));
System.out.println(card.get(x));
}
return hand;
}//end of public void deal
}// end of public class deck
then i have the main
import java.util.ArrayList;
import java.util.*;
public class gamePlay
{
private static gamePlay player1;
public Deck fullDeck;
private ArrayList<Card> yourHand;
public gamePlay()
{
fullDeck=new Deck();
System.out.println("Your poker hand is a");
yourHand = fullDeck.deal();
//System.out.println(yourHand);
}
public static void main(String[] args)
{
player1 = new gamePlay();
}
}
It is printing out some crazy stuff for the value and suit of the cards in the hand
i think they are either memory locations from the arraylist or hexidecimal values i am not sure need it to print suit and rank any help is appreciated

If your classes implement a proper toString method, it will show up perfectly.
You can easily change your existing method displayCard in the Card class to a toString method. This leads to more flexibility than to let the Card print out itself by calling System.out.println in the card's method.
#Override
public String toString() {
return value + " of " + suit;
}
If you want the card to print to System.out you just do System.out.println(card);
Normal arrays can also be converted to String, using Arrays.toString(array) (if you would have a Card[] variable for example). Most implementations of Lists already implement a proper toString method so it will show you a comma-separated list of the entries.

You have to provide a toString() method in your Card class.
For example:
#Override
public String toString() {
return String.format("Card [value=%s, suit=%s]", value, suit);
}
If you don't provide that method, the default depends on the JDK implementation. Usually, it is the name of the class followed by a # and the object hash code.

I suspect that you have to iterate through the array and print each item individually. One cannot print the entire content of an array by toString() the array itself.

Related

Problems on poker game and comparator?

I am trying to create a poker game in which I create the deck in the Card class, and use a comparator to sort the deck in alphabetical order. I'm having trouble with what to put in the comparator, and in my dealer class, (this is where I create the deck, shuffle, as well as calling the comparator). When my CompareCards does compile, my Dealer class will give me the error of:
Dealer.java:24: error: incompatible types: void cannot be converted to String
String s = Collections.sort(deck);
^
Note: Dealer.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
I know that when doing the sort, you have to include the Comparator name, but in this case it doesn't work either way. Here is my card class:
import java.util.*;
public class Card{
String suit = null;
String value = null;
String rank = null;
public static final String[] SUIT = {"C", "D", "H", "S" };
public static final String[] RANK = {"A","2","3","4","5","6","7","8","9","T","J","Q","K"};
public Card(int i, int j){
suit = RANK [i];
rank = SUIT [j];
value = rank + suit;
}
public String getSuit(){
return suit;
}
public String getRank(){
return rank;
}
public String toString(){
return(value);
}
}
Here is my Comparator and CompareCards class:
public interface Comparator <Card>{
public int compare(Card o1, Card o2);
}
public class CompareCards implements Comparator<Card>{
public int compare(Card c1, Card c2){
int x = 0;
int y = 0;
int dx = c1.getRank() - c2.getRank();
if(dx == 0){
x = c1.getRank()-c2.getRank();
}
else{
y = c1.getSuit() - c2.getSuit();
}
return x;
}
And here is the dealer class:
import java.util.*;
public class Dealer{
public static void main(String[]args){
// creating deck
List<Card> deck= new ArrayList<Card>();
// calling Card
for(int i = 0; i < 13 ; i++){
for(int j = 0; j < 4 ; j++){
// String s = RANK[i] +SUIT[j];
deck.add(new Card(i, j));
}
}
finding21(deck);
}
public static void finding21 (List deck){
String s = Collections.sort(deck);
System.out.println("Sorted deck: " + s);
// After I sort the deck I am supposed to do a binary search
// for the queen of hearts
/* Collections.shuffle(deck);
System.out.println("Shuffled deck: " + deck);
String HQ = Collections.binarySearch(deck, "HQ");
System.out.print(HQ);
System.out.println(queenH);*/
}
}
Collections.sort does an in-place sort and does not return a value.
That's why the compiler says you can't convert a void to a String.
The void type is used for functions with no return value.
Just use:
Collections.sort(deck);
If you want to print the sorted deck after, you can use:
System.out.println("Sorted deck: " + deck);

Can't seem to print an arraylist full of objects/enums

I was trying to create a card game golf for fun and to practice my java skills. I'm trying to use enums for my card values and suites. Those values are held in a constructor, named Card, in the Card Class.
The problem I'm running into to is printing my arraylist Deck that holds all my individual cards. This method can be found in the DeckOfCards Class . I want to see if my program is creating a full deck of cards. Thanks in advance for the help!
DeckOfCards Class
package finalProjectGolf;
// Deck class represent a deck of playing cards.
import java.util.ArrayList;
import java.util.Collections;
public class DeckOfCards {
ArrayList<Card> deck = new ArrayList<Card>(); //array of Card objects
private int currentCard; // index of next Card to be dealt (0-51)
private static int numDecks = 1;
public int getCurrentCard() {
return currentCard;
}
public void setCurrentCard(int currentCard) {
this.currentCard = currentCard;
}
private static final int NUMBER_OF_CARDS = 52 * numDecks; //constant # of Cards
//constructor fill deck of Cards
public DeckOfCards(){
currentCard = 0; //set currentCard so first Card dealt is deck[0]
//Card Index
int c = 0;
//for each deck
for (int d = 0; d < numDecks; d++){
//for each suit
for (int s = 0; s < 4; s++){
// for each number
for (int n = 1; n <= 13; n++){
//add a new card to the deck
deck.add(new Card(CardValue.values()[n],Suit.values()[s])); //when using Enums java makes arrays automatically and you can use them by .values()
c++;
}}}//end for loop
}//end DeckOfCards constructor
//shuffle deck of Cards with one-pass algorithm
public void shuffle() {
Collections.shuffle(deck);
}
public int points(){
int value = deck.get(currentCard).getCardValue().getCardValue();
return value;
}
//deal one Card
public Card dealCard(int currentCard) {
//determine whether Cards remain to be dealt
if( currentCard < deck.size() ){
return deck.get(currentCard); //return current Card in array
}
else
return null; // return null to indicate that all Cards were dealt
}//end method dealCard
public void printDeck(){
{
currentCard = 0; //set currentCard so first Card dealt is deck[0]
//Card Index
int c = 0;
//for each deck
for (int d = 0; d < numDecks; d++){
//for each suit
for (int s = 0; s < 4; s++){
// for each number
for (int n = 1; n <= 13; n++){
//add a new card to the deck
System.out.printf(""); //when using Enums java makes arrays automatically and you can use them by .values()
c++;
}}}//end for loop
}//end DeckOfCards constructor
}
}// end class DeckOfCards
Card Class
package finalProjectGolf;
public class Card
{
private Suit suit;
private CardValue cardValue;
public Card (CardValue cardValue, Suit suit) //constructor of Card, holds Card value and it's suit
{
this.cardValue = cardValue;
this.suit = suit;
}
public Suit getSuit()
{
return suit;
}
public void setSuit(Suit suit)
{
this.suit = suit;
}
public CardValue getCardValue()
{
return cardValue;
}
public void setCardValue(CardValue cardValue)
{
this.cardValue = cardValue;
}
public String toString(){
return cardValue + " of " + suit;
}// end method toString
}
CardValue Class
package finalProjectGolf;
public enum CardValue
{
ACE(1),
TWO(2),
THREE(3),
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9),
TEN(10),
JACK(11),
QUEEN(12),
KING(13);
private int cardValue;
private CardValue (int value)
{
this.cardValue = value;
}
public int getCardValue() {
return cardValue;
}
}
Suit Class
package finalProjectGolf;
public enum Suit
{
HEARTS(1),
SPADES(2),
CLUBS(3),
DIAMONDS(4);
private int suit;
private Suit (int value)
{
this.suit = value;
}
public int getCardSuit() {
return suit;
}
}
To add to AaronB's answer, your printDeck method is in fact wrong, as you have posted it. Currently it prints the empty string 52 times. In addition, you don't need to triple for loop just to print all the items in your deck. A very simple implementation that prints each card on a new line for a single deck would be:
public void printDeck() {
for(Card card : deck) {
System.out.println( card.toString() );
}
}
You also need to override the toString method for your enum values so that they print the name you want. Have a look at https://stackoverflow.com/a/14413605/1425014 for how to do that.
Your main class is called DeckOfCards. That indicates to me that the class represents a single deck of cards. However, judging by for (int d = 0; d < numDecks; d++) and private static int numDecks = 1, it appears that you intend for DeckOfCards to represent one or more decks of cards. It may be clearer to simply uses a collection (such as ArrayList) if you need more than on DeckOfCards instead of complicating the DeckOfCards class.
Finally, you should try to make sure your comments make sense before you post your code here. The comments for your printDeck() function haven't been changed after you copy/pasted from the DeckOfCards constructor.
The problem isn't that your printDeck method doesn't work (I haven't tested it yet, but at first glance it looks reasonable), it's that you never call it. You could place it at the end of the DeckOfCards constructor, if the point is to check that it's all there correctly.
In addition, you really should refactor a bunch of your logic, most notably in the DeckOfCards class. You've got some big blocks of computation -- put that in a method. Also, instead of declaring variables in the class, you should declare them in the constructor. For example:
ArrayList<Card> deck; //array of Card objects
private int currentCard; // index of next Card to be dealt (0-51)
private static int numDecks;
//constructor fill deck of Cards
public DeckOfCards(int numDecks){
deck = new ArrayList<Card>();
currentCard = 0; //set currentCard so first Card dealt is deck[0]
this.numDecks = numDecks;
Correct me if I'm wrong though, you didn't really describe what the issue was...

Issue printing out objects from arraylist

First i have a class called card with this code
public class Card
{
private int value;
private String suit;
// private int value;
//private String rank;
public Card (int v, String s)
{
value=v;
suit=s;
}
public int random()
{
int randomNum = ((int)(Math.random() * 100) % 13 +1);
return randomNum;
}
public void displayCard()
{
System.out.println(value + " of " + suit);
}
}
then i have a class called deck with this code
import java.util.*;
public class Deck
{
public ArrayList<Card> card;
private ArrayList<String> suits;
private ArrayList<Card> hand;
public Deck()// time to build a deck
{
card=new ArrayList<>();
suits=new ArrayList<>();
suits.add("Hearts");
suits.add("Spades");
suits.add("Clubs");
suits.add("Diamonds");
for (int y=2; y<15; y++)
{
card.add(new Card(y,suits.get(0)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(1)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(2)));
}
for (int y=2; y<15; y++)
{
card.add(new Card((y),suits.get(3)));
}
}//end of public deck
public ArrayList deal()// deal method
{
hand=new ArrayList<>();
for(int x = 0; x < 5; ++x)//build 5 card hand
{
hand.add(card.get(x));
System.out.println(card.get(x));
}
return hand;
}//end of public void deal
}// end of public class deck
then i have the main
import java.util.ArrayList;
import java.util.*;
public class gamePlay
{
private static gamePlay player1;
public Deck fullDeck;
private ArrayList<Card> yourHand;
public gamePlay()
{
fullDeck=new Deck();
System.out.println("Your poker hand is a");
yourHand = fullDeck.deal();
//System.out.println(yourHand);
}
public static void main(String[] args)
{
player1 = new gamePlay();
}
}
It is printing out some crazy stuff for the value and suit of the cards in the hand
i think they are either memory locations from the arraylist or hexidecimal values i am not sure need it to print suit and rank any help is appreciated
If your classes implement a proper toString method, it will show up perfectly.
You can easily change your existing method displayCard in the Card class to a toString method. This leads to more flexibility than to let the Card print out itself by calling System.out.println in the card's method.
#Override
public String toString() {
return value + " of " + suit;
}
If you want the card to print to System.out you just do System.out.println(card);
Normal arrays can also be converted to String, using Arrays.toString(array) (if you would have a Card[] variable for example). Most implementations of Lists already implement a proper toString method so it will show you a comma-separated list of the entries.
You have to provide a toString() method in your Card class.
For example:
#Override
public String toString() {
return String.format("Card [value=%s, suit=%s]", value, suit);
}
If you don't provide that method, the default depends on the JDK implementation. Usually, it is the name of the class followed by a # and the object hash code.
I suspect that you have to iterate through the array and print each item individually. One cannot print the entire content of an array by toString() the array itself.

Return array in Java

I have my primary class running, and I wanted to run a separate class to shuffle numbers, then return the shuffled numbers into my primary class. In my shuffle class I have the return statement... but now what do I do? How do I use the random order of my int array in my primary class?
Here is my shuffle class:
public class Shuffle {
public static int[] getShuffle() {
int[] cards = new int[52];
ArrayList<Integer> cards_objs = new ArrayList<Integer>();
for (int i = 0; i < cards.length; i++) {
cards_objs.add(i);
}
Collections.shuffle(cards_objs);
for (int i = 0; i < cards.length; i++) {
cards[i] = cards_objs.get(i);
}
return cards;
}
}
I am making a card game(if you cant tell);
I wanted to use this shuffle class so that the cards are shuffled... but no card appears more than once.
when I return cards, how do I use them in my game class?
for example if the first number in the array is 1, then the card is Ace of clubs,
if the number is 2, then the card is Ace of diamonds. and so on...
I apologize for not posting enough information... I am new to java (as you can tell)
all help will be greatly appreciated,
-Steve
EDIT:
I found out what my problem was, I don't think I made it clear enough what my question was. Nonetheless thank you all for your help, it gave me ideas on different ways to approach this project.
I think using enum you can implement Card Game in a better way.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// This is just sample example and it is just to show an approach. I had not enough time to make code perfect but it works fine.
public enum Deck
{
DECK;
enum Rank
{
DEUCE(2), THREE(3), FOUR(4), FIVE(5), SIX(6),
SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);
Rank(int rank)
{
this.rank = rank;
}
private final int rank;
}
enum Type
{
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
class Card
{
private final Rank rank;
private final Type type;
Card(Rank rank, Type type)
{
this.rank = rank;
this.type = type;
}
#Override
public String toString()
{
return type.name() + rank.name();
}
}
static List<Deck.Card> cards = new ArrayList<Deck.Card>();
static
{
for (Rank rank : Deck.Rank.values())
{
for (Type type : Deck.Type.values())
{
cards.add(DECK.new Card(rank, type));
}
}
}
List<Deck.Card> shuffle()
{
Collections.shuffle(cards);
System.out.println(cards);
System.out.println(cards.size());
return Collections.unmodifiableList(cards);
}
public static void main(String[] args)
{
DECK.shuffle();
}
}
No need to define seperate class i feel, Just create an arraylist of numbers, pass it to Colections class of java
public static void shuffle(List list)
Your list will be shuffled directly
Either you change the array order so you can iterate the normal order in the array in your main class or you return an array back from your shuffle methode which contains the order (index) desired then access these up to this order.
Option A is to change the roder of the elemtns of your main array and Option B is to read the array and decide determin the new order, and return the order as ana rray backt, then access the main array up tot he new order.
You can simply have a method in you main class where you can do the shuffling and return the new set of shuffled numbers as an array.
If you do want to use another class, then you can do that using the instance of the class, and then call that reShuffleNumbers(), whereas reShuffleNumbers() will return array of numbers as you've wanted.
Try this -
public static void shuffleArray(int[] a) {
int n = a.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
swap(a, i, change);
}
}
private static void swap(int[] a, int i, int change) {
int helper = a[i];
a[i] = a[change];
a[change] = helper;
}
Pass the array to method shuffleArray() and you will get your array elements modified by position.
I hope this is what you are looking for.

Hand of cards: Total value (Java)

I am currently working on a hand of cards class that uses enums that requires me to add methods that:
Add cards into the hand
Calculate the total value of all the cards currently in the hand (so if there were 3 10's in the hand then the total value would be 30)
The problem however is that I can't find out how to add up all the total while still implimenting the method within the hand class (as the task asks us to).
Any help will be greatly appreciated
Heres the code for my Suit enum
public enum Suit
{ HEARTS, CLUBS, DIAMONDS, SPADES; }
Here is the code for my Rank enum.This one has a few added methods including a getValue method
public enum Rank {
ONE(1),TWO(2),THREE(3),FOUR(4),FIVE(5), SIX (6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), KING(10), QUEEN(10),
JACK(10);
private final int cardValue;
private Rank ( int nDays) {
cardValue = nDays;
}
public int getValue() {
return cardValue;
}
}
This is the Card class that uses the Rank and Suit enums to print off the details (excuse the mess)
public class Card {
private Rank rank;
private Suit suit;
public Card (Rank theRank) {
this(theRank,Suit.HEARTS);
}
public Card (Rank theRank, Suit theSuit) {
rank = theRank;
suit = theSuit;
}
public Rank getRank( ) { return rank; }
public Suit getSuit ( ) { return suit; }
public String toString ( ) { return ( rank + " of " + suit +"\n Value of card = " + rank.getValue() ); }
}
And this is the Hand class that requires the addCard method and the totalValue method. I have done the addCard method and now need to do totalValue method)
public class Hand {
private Card theCards[ ];
private Rank rank;
private int numCards; private int totalValue;
private static final int max = 5;
public Hand ( )
{
theCards = new Card [max];
numCards = 0;
}
public void addCard( Card aCard )
{
if (numCards < max)
theCards[numCards++] = aCard;
else
{
System.out.println("Cannot add any more cards as hand is full");
}
}
public void totalValue ()
{
int handValue = 0;
for(Card C: theCards)
{
//get the rank values to appear then print them off
//Add up all values of cards and display the total
totalValue = handValue + C.getValue(); //This was just a test to see if calling up the value of card C would work
}
System.out.println("The total value of all the cards is: " + totalValue);
}
public String toString ( )
{
String s = "";
for (int i = 0; i < numCards; ++i) { s += "\n" + theCards[i];
}
return s;
}
As far as implimentation goes its just a case of creating card objects and adding them to the Hand object so I don't think I'll need to post that here. Thank you to anyone who can help me with my problem.
Card doesn't have a getValue() method but Rank does. So get the card's Rank via its getRank() method and then call getValue() on the rank returned.
The value of a Card is available through its rank field. Right now you are trying to call getValue() directly on the Card, but there's no such method (yet).
Also, you'd normally return the total value of the hand from the totalValue() method, rather than simply printing it; this allows other code to actually use the value.
I managed to figure out how to make it print without returning any nullexception errors. Basicly I simply converted the array into an arraylist as it was much more practical. Here is the final version of the Hand class.
import java.util.*;
public class Hand {
private ArrayList<Card> theCards = new ArrayList<Card >() ;
private static final int max = 5;
public void addCard( Card aCard )
{
if (theCards.size() < max)
theCards.add(aCard);
else
{
System.out.println("Cannot add any more cards as hand is ull");
}
}
public void totalValue() {
int totalValue = 0;
for (Card card : theCards) {
totalValue += card.getRank().getValue();
}
System.out
.println("The total value of all the cards is: " + totalValue);
}
public void outputAllCards ( )
{
System.out.println("Outputting all card etails\n========================");
for (Card card : theCards)
{
System.out.println(card.toString());
}
System.out.println("========================");
} }
I put in a println in order to print a message out when the totalValue method was called. I tried returning by turning the method into a string or int but this didn't work
The value is inside the rank. Does the rank object inside hand play any role (such as doubling value of the corresponding cards in the hand, you have to specify the game rules)? You just have to add up the rank values. I rewrote your code to leave out some unneccessary counters/vars. On the other side it is better to keep a list instead of an array if it can grow.
import java.util.ArrayList;
import java.util.List;
public class Hand {
private final List<Card> cards = new ArrayList<Card>();
private Rank rank;
private static final int MAX = 5;
public void addCard(Card aCard) {
if (cards.size() < MAX) {
cards.add(aCard);
} else {
System.out.println("Cannot add any more cards as hand is full");
}
}
public void totalValue() {
int totalValue = 0;
for (Card card : cards) {
totalValue += card.getRank().getValue();
}
System.out
.println("The total value of all the cards is: " + totalValue);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (Card card : cards) {
sb.append('\n').append(card.toString());
}
return sb.toString();
}
}

Categories