Java Arraylist get method - java

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.

Related

How do I call a class into another class?

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.

Need help adding card elements to my Array List

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.

When trying to print out a constructor, I get the constructor name and a time stamp

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);
}

How to Split a deck of cards in half?

I'm trying to create a really simple game of war. User and computer draws 1 card per turn, they either win, tie, or lose. Game is over when cards are out. I have 4 classes. My war class I was mostly just testing out if things were working for the deck. What I need to do is split the deck in half so each player draws 1 card each turn (A total of 26 by the end of the game) and I don't know how to do that. I'm guessing I need a for loop, but other than that I don't know how I would give each player a card. Ignore the user input in Class War, like I said, I was just testing things out. I have 3 classes displayed here, my last one is a JApplet which isn't need here so I haven't included it.
EDIT: Thanks for the help guys. I have one last problem and then I should be good. I want to display Card.toString inside my JApplet class but when I call Card card = new Card(); it refuses to work. I'm guessing this is because of the constructor. How would I go about getting that toString to display, or bypass the constructor.
Edit: Figure everything out, Thanks for the help guys.
import java.util.ArrayList;
import java.util.Random;
public class Card {
private int suit, number;
String [] suits = {"Heart" , "Diamond" , "Spade" , "Club"}; //suits
String [] numbers = { "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "10" ,
"Jack" , "Queen" , "King" , "Ace" }; //card values
String card = "";
public Card(int suits, int numbers)
{
suit = suits;
number = numbers;
}
public String toString() //displays card suit/value
{
String finalCard = numbers[number] + " of " + suits[suit];
return finalCard;
}
}
import java.util.ArrayList;
import java.util.Random;
public class FullDeck {
private ArrayList<Card> cards = new ArrayList<Card>();//card array list
public FullDeck()
{
for(int a =0; a<=3; a++) //loops through suits
{
for(int b =0; b<=12;b++) //loops through values
{
cards.add(new Card(a,b)); //creates adds cards to list
}
}
}
public Card drawRandomCard()
{
Random generator = new Random(); //picks random card
int index = generator.nextInt(cards.size());
return cards.remove(index); //removes card from list
}
public String toString()
{
String result = "Cards remaining in deck: " + cards; //not currently used
return result;
}
}
import java.util.Scanner;
public class War {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Card C;
FullDeck hand1 = new FullDeck();
FullDeck hand2 = new FullDeck();
System.out.println("Enter number of cards to be dealt: ");
int numberCards = scan.nextInt();
System.out.println("Cards drawn: ");
for (int i = 0; i < numberCards; i++) {
C = hand1.drawRandomCard();
System.out.println(C.toString());
}
}
}
Create two ArrayList<Card>s, then make a for loop that goes through 52 times.
for(int i=0;i<52;i++){
Card tempCard = hand1.getCards().remove(hand1.getCards().indexOf(hand1.drawRandomCard()));
if(i%2 == 1){
firstPlayersCards.add(tempCard);
}else{
secondPlayersCards.add(tempCard);
}
}
Make sure to add a getCards() method in FullDeck which just returns cards.
And this way all of the cards are randomized in each player's hands, so you can just get them in order.
Edit: though, the simplest solution is what Daniel Gabriel said and to just call drawRandomCard() twice in a row.
It'd make sense to rename your FullDeck class to just Deck...
Then, include a constructor for Deck that takes an ArrayList as a parameter. Include a method for Deck that returns a Deck object and is called something like splitDeck.
Internally, the splitDeck takes half the cards in Deck, removes them from cards on that object, and adds them to a new, temporary ArrayList. Then, it creates and returns an a deck object built using this temporary ArrayList.
public Deck(ArrayList<Card> deck) {
cards = deck;
}
public Deck splitDeck() {
ArrayList<Card> temp = new ArrayList<>();
for(int i = cards.length() - 1; i >= cards.length()/2; --i) {
temp.add(cards.get(i));
cards.remove(i);
}
return new Deck(temp);
}
Now the Deck object on which you called the method contains half a deck, and the Deck object returned contains the other half.
Assuming you rename the class to Deck (just because it'd make more sense) and kept the same default constructor:
Deck playerOneDeck = new Deck();
// playerOne now has a full deck of cards
Deck playerTwoDeck = playerOneDeck.splitDeck();
// playerOne and playerTwo now each have half of playerOne's original full deck

How can I call my array to my main class?

I have one class called DVD collection and another one called movies. The method with the array that I'm trying to return looks like this:
public class DVDCollection
{
public static DVD[] collection;
public static void searchForDVD( String DVD[], String a) {
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++) {
System.out.print(DVD[i] + a);
}
System.out.println();
}
}
And I'm trying to call it from my main method like so:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
movies.searchForDVD(DVD);
}
}
But it gives me an error saying cannot find symbol - variable DVD
So what exactly is the problem here?
You're calling
movies.searchForDVD(DVD);
but there is no DVD variable defined in the main method. And BTW, even if there was one, the searchForDVD() method takes two arguments, and not just one.
Also note that the searchForDVD() method is static. So you don't need any instance of DVDCollection to call it. Instead of
DVDCollection movies = new DVDCollection();
movies.searchForDVD(...);
you should use
DVDCollection.searchForDVD(...);
In your main method when calling the searchForDVD method you must pass it an array of strings for the dvds along with the name of the dvd as a string.
At the moment you are passing the variable DVD which you have not declared anywhere in the main method.
Code in main method should be:
String[] dvds = new String[] {"firstDVD","secondDVD","thirdDVD");
String movie = "secondDVD";
DVDCollection.searchForDVD(dvds,movie);
problem 1
movies.searchForDVD(DVD);
the parameter DVD is not defined.
problem 2
public static void searchForDVD(...) is a static method of class DVDCollection you should call it DVDCollection.searchForDVD(...) you don't need the movie object.
You are calling DVD several times in this code. I believe the mistake here is the variable name.
You have defined public static DVD[] collection; which is an array of DVD objects called collection. The variable name is collection and that is what you need to use when referencing the variable.
ie: collection.length instead of DVD.length.
When you say public static DVD[] collection;, you are telling the compiler to create you a public, static Array of DVD objects called collection. At some point this array would need to be initialized. Arrays are initialized in the following format:
DVD[] collection = new DVD[];
or
String[] arrayOfStrings = {"a","b","c","d"};
Another problem is that your method is defined as follows:
public static void searchForDVD( String DVD[], String a)
This method is requiring two arguments, not one. If you are trying to require a String[] array called "DVD" then you should declare as follows:
public static void searchForDVD( String[] DVD, String a)
That declaration says this method takes an array of strings and we'll call it DVD and another String which will be called a.
Make sure to note what your variable type is and what your variable name is.
The type tells java what to expect in the variable, the name is how you access it.
String myString = "string data";
String is the type. myString is the variable name. "string data" is the value assigned to the variable.
What makes sense to me is something like:
public class Movies
{
public static void main (String[] args)
{
DVDCollection movies = new DVDCollection();
//create an Add function inside DVDCollection which reads lines from a text file into collection
movies.Add("list_of_movies.txt");
// no arguments are needed here imo, just have it print to user to ask for a DVD to search and then search the collection
movies.searchForDVD();
}
}
public class DVDCollection
{
public DVD[] collection;
public void Add(string file)
{
// parse file and add contents to collection
}
public void searchForDVD()
{
System.out.println("What DVD would you like to search for?");
Scanner scan = new Scanner(System.in);
a = scan.nextLine();
int N = DVD.length;
for (int i = 1; i < N; i++)
for (int j = i; j > 0; j--)
if (DVD[j-1].compareTo(DVD[j]) > 0)
change(DVD, j, j-1);
else break;
for (int i = 0; i < DVD.length; i++)
{
System.out.print(DVD[i] + a);
}
System.out.println();
}
}

Categories

Resources