package decks;
import java.util.ArrayList;
public class hand {
private ArrayList<card> hand;
private card test;
public hand(){
hand = null;
}
public void clear(){
for (int x = hand.size() - 1; x >= 0; x--)
hand.remove(x);
}
public void addCard(card c){
hand.add(c);
}
public void removeCard(card c){
if (hand.contains(c))
hand.remove(c);
}
public void removeCard(int pos){
hand.remove(pos);
}
public int getCardCount(){
return hand.size();
}
public String toString(){
String toReturn = "";
for (card n : hand)
toReturn += n + "\n";
return toReturn;
}
}
Alright so I have to make a card game for homework at my school, and so far we've made a card, deck, and hand class plus a runner. We built the decks and hands using Array Lists. I was trying to test it out by adding a card to the deck by using:
pOne.addCard(test);
The only thing in the addCard class is:
public void addCard(card c){
hand.add(c);
}
This however, only returns an error, it never actually adds a card to the ArrayList hand. Any ways to fix this? PLease help
You initialize the List to null in the constructor. Instantiate the List instead. Something like,
public hand(){
// hand = null;
hand = new ArrayList<>();
}
Also, by convention, Java class names start with a capital letter. So, I would prefer classes Hand and Card (instead of hand and card). Finally, for clear, you can call List.clear() instead of using a loop.
Related
I do not get how to put the Card class into the Deck. Would you please explain how I can fix this?
Here are the instructions:
You need to rewrite the constructor so that all 52 cards of a normal card deck are assigned to the cards array. Keep in mind that card information needs to be stored inside the Deck class and is not passed by parameter. Additionally, you need to re-define the toString method for the Deck class so that it can be used to display the attribute values in a convenient manner. Make sure to take advantage of the toString method that already exists in the Card class.
(You also need to add a shuffle method, which is called from the constructor. The shuffle method is a private helper method in the Deck class. For this version you need to shuffle the deck by swapping the cards. Generate two random numbers in the [0..51] number range that will represent the indexes of the cards array and swap the cards. Make 1000 swaps and then display the cards. Use Math.random to generate random numbers.) <-This is a part of the instructions, but I don't think it matters in this situation because I what I want to know is how to do put the Card class in to the Deck.(but i still put it in just in case)
public class Lab11bvst
{
public static void main(String[] args)
{
Deck deck = new Deck();
System.out.println(deck);
}
}
class Deck
{
private Card[] cards;
private int size;
private String[ ] suits = {"Clubs","Diamonds","Hearts","Spades"};
public Deck()
{
size = 52;
cards = new Card[size];
}
private shuffle(){
}
}
the Card class:
public class Card
{
private String suit;
private String rank;
private int value;
public Card(String s, String r, int v)
{
suit = s;
rank = r;
value = v;
}
public String getSuit() { return suit; }
public String getRank() { return rank; }
public int getValue() { return value; }
public void setSuit(String s) { suit = s; }
public void setRank(String r) { rank = r; }
public void setValue(int v) { value = v; }
public String toString()
{
return "[" + suit + ", " + rank + ", " + value + "]";
}
public boolean matches(Card otherCard)
{
return otherCard.getSuit().equals(this.suit)
&& otherCard.getRank().equals(this.rank)
&& otherCard.getValue() == this.value;
}
}
"rewrite the constructor so that all 52 cards of a normal card deck are assigned to the cards array"
Right now, the constructor is setting the size of the deck to 52 cards, and then it initializes an array to hold 52 elements. You'll need to populate the cards array by creating cards for all 52 cards normally found in a deck. The constructor of your Card class helps you do this.
For example, you could start by adding an Ace of Diamonds and adding it to the cards array:
Card aceD = new Card("Diamonds", "Ace", 1);
cards[0] = aceD;
and then add all 52 cards to your cards array.
My name is Chris!
To help improve my java programming skills, I'm trying to make a deck class which is an array of cards, however when printing the constructor for the deck class, I get the constructor name and a time stamp and I am COMPLETELY clueless as to why this is.
Can you help?
public static void main(String args[])
{
System.out.println("Custom Java Card Game- Chris L.");
System.out.println();
Deck deck = new Deck();
deck.addCards();
System.out.println();
System.out.println(deck);
}
That is the code from the main program and here is the deck class:
public Deck() //Deck is an array of cards
{
size = 52;
cards = new Card[size]; //Array of cards up to 52
// addCards();
}
public void addCards(){
for(int k = 0; k < Slength; k++){
for (int m = 0; m < Rlength; m++){
String s = suite[k];
String n = num[m];
int r = rank[m];
String str = Integer.toString(r);
// String fin = "[" + s + "," + n + "," + str + "] \r";
// System.out.print(fin);
Card card0 = new Card(s,n,r); //Makes a card! IS WORKING!
turntoString(card0);
// System.out.println( turntoString(card0) );
cards[k] = card0; //adds card to array! IS WORKING!
// System.out.println(cards); //card0
System.out.println(turntoString(card0));
}
}
and here is the output:
deck.Deck#1f01b29
Can anybody explain to me why this is?
You must override the toString() method in the Deck class, otherwise the default method from Object is used, which doesn't print a very useful text. Perhaps something like this:
#Override
public String toString() {
return "the text that you want to print";
}
You might want to return the values of the attributes in the class, or some other information that you deem useful.
You are printing the object information itself since it doesn't have a toString() method to use in order to print it in a human readable way.
#Override
public String toString() {
return "Any text";
}
Remember, you can override toString, equals( & hashcode) for conveniece
eg.
Comparing an instance of Deck to another deck
#Override
public boolean equals(Object object) {
return this.size == ((Deck) object.size);
}
import java.util.*;
public class Deck {
public int deckSize = 52;
public ArrayList<Card> deck1 = new ArrayList<Card>(deckSize);
public Deck() {
for (CardEnum card : CardEnum.values()) {
for (SuitEnum suit: SuitEnum.values()) {
Card newCard = new Card(card, suit);
this.deck1.add(newCard);
}
}
}
int size() { return this.deck1.size(); }
String draw() {
Iterator<Card> itrCard = deck1.iterator();
if (!itrCard.hasNext()) {
throw new IndexOutOfBoundsException("Deck is empty!");
}
Card next = itrCard.next();
String name = next.getName();
this.deck1.remove(next);
return name;
}
void shuffle() {
Collections.shuffle(this.deck1);
}
public static void main(String[] args) {
Deck deck1 = new Deck();
deck1.shuffle();
System.out.println("The first five cards drawn are:");
for (int i = 0; i<5; i++) {
System.out.print(deck1.draw() + " ");
}
System.out.println("\n");
for (int i = 0; i<5; i++) {
System.out.print(deck1.draw() + " ");
}
System.out.println(deck1.get(1));
System.out.println("\nHow many cards do you want to replace? (Max of 4)");
Scanner in = new Scanner(System.in);
int v;
v = in.nextInt();
}
//System.out.println(deck2.get(4));
}
For this segment of code it says the method get is undefined for the type Deck? How can I make the get method work? Also I am trying to be able to create a function to replace up to 4 of the cards. I can deal out old cards, but how can I keep the old ones. I also need to be able to evaluate the hand and tell what it is (full house, pair, etc). I am finding this to be quite difficult, so even if you can only answer one of my questions, I would greatly appreciate it.
The Deck class itself has no get(int) method, however, you attempt to call this method on an Object of type Deck in your main() method. In order for this code to compile, you will need to write a method called get that takes an int as its argument.
Although the Deck class has an internal variable named deck1 that is an ArrayList, the scope of this method is limited to code within the Deck class. When you create a Deck named deck1 in main, this is a different object from the ArrayList named deck1 that is defined in the Deck class. Although they have the same name, these are two different objects, so this deck1 is not an ArrayList and cannot access the methods that ArrayList offers.
You just need to add a get method somewhere in your Deck class that forwards to the get method of your backing ArrayList. For example:
public class Deck {
public int deckSize = 52;
public ArrayList<Card> deck1 = new ArrayList<Card>(deckSize);
public Card get(int i) {
return deck1.get(i);
}
Alternatively, just use the public field:
System.out.println(deck1.deck1.get(1).getName());
^ ^
| └-- public field
└--local variable
It's a bit confusing because you've given your local Deck variable the same name as your ArrayList field in the Deck class.
How to swap the position of two cards in the deck of ArrayList<Card>?
public class Deck
{
private ArrayList<Card> deck;
public Deck()
{
deck = new ArrayList<Card>();
}
public void addCard(Card cardToAdd)
{
deck.add(cardToAdd);
}
}
The supplied code is Java, so we'll go with Java.
Add a method, called swapCards like so:
public void swapCards (int indexA, int indexB)
{
Card temp = deck.get (indexA);
deck.set(indexA, deck.get (indexB));
deck.set(indexB, temp);
}
Now, some thing to think about:
What happens if indexA and indexB are beyond the size of the deck, how should the class behave?
Is there a better way to design the class? Are card indicies the best parameters to use here, could we do something else?
so I'm currently doing an exercise for college that has several optional parts (because we havn't done this in class yet), one of them being to use lists instead of arrays (so it'd be variable size) and another one printing the list sorted by points (I'll get to that now)
So, I have the Player.java class which looks like this.
public class Player {
String name;
String password;
int chips;
int points;
public Player(String n, String pw, int c, int p) {
name = n;
password = pw;
chips = c;
points = p;
}
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public void setPW(String pw) {
password = pw;
}
public String getPW() {
return password;
}
public void setChips(int c) {
chips = c;
}
public int getChips() {
return chips;
}
public void setPoints(int p) {
points = p;
}
public int getPoints() {
return points;
}
}
Pretty simple, then I'm creating a List with this (in another class):
List<Player> lplayer = new ArrayList<Player>();
Adding players with this:
lplayer.add(new Player(n,pw,c,p))`
And finally reading their stats with this:
public int search_Player (String n) {
String name;
int i = 0;
boolean found = false;
while ((i <= tp) && (!found)) {
name = lplayer.get(i).getName();
if (name.equals(n)) {
found = true;
}
i++;
}
return (found == true) ? i-1 : -1;
}
public Player show_Player (int i) {
return lplayer.get(i);
}
public void list_Players() {
Collections.sort(lplayer);
int i2;
if (tp > 0) { // variable which contains number of total players
for (int i = 0;i<tp;i++) {
i2 = i+1;
System.out.println ("\n"+i2+". "+lplayer.get(i).getName()+" [CHIPS: "+lplayer.get(i).getChips()+" - POINTS: "+lplayer.get(i).getPoints()+"]");
}
}
else {
System.out.println ("There are no players yet.");
}
}
So that's basically all the code. As you can see the I already have a list_Players function but that just prints it in the order it was added. I need a way to print in sorted by the points each player has (so basically a ranking).
As you can see I'm pretty new to java so please try not to come up with a very complicated way of doing it.
I've already searched for it and found things like Collections.sort(list) but I guess that's not what I need right here.
Thank you!
You can use the public static <T> void sort(List<T> list, Comparator<? super T> c) overload in Collections - provide the comparator you need (can be just an anonymous class) - and you are all set!
EDIT:
This describes how the method works. In brief, you'll implement your call as
Collections.sort(list, new Comparator<Player>() {
int compare(Player left, Player right) {
return left.getPoints() - right.getPoints(); // The order depends on the direction of sorting.
}
});
That's it!
Collections.sort(list) could definitely by a solution for your problem. It's a way to sort your collections provided by Java. If you are writing a "real world" application (not an exercise for collage) this would be the way you doing it.
To let Collections.sort(list) works, you have to implement an interface call Comparaple. By implementing this interface, the sort will know how to order your elements.
But because it's a exercise for collage, this is perhaps a little bit to easy. If you want (or must) implement you own sorting algorithm, try first to sort a common list of numbers (1, 5, 2, 7...). You can extend such an sorting algorithm easily for your own classes.
A new approach using lambdas, that is a lot shorter to write is
myList.sort((obj1, obj2)->(condition)?1:-1);
where you can use the objects for your condition, and anything greater than 0 returned means swap (in this case if condition returns true)