I'm trying to deal a card (the object) from my deck (the arraylist) and I'm having trouble trying to get the first object in the arraylist.
I've used a shuffle method (which is working and prints out the total number of cards in the newly shuffled pack) but I have no idea how to get the first object from the array (ie dealing a card from the top).
Can anyone point me in the right direction please?
Thanks.
Take a look at the ArrayList.get(int index) method. It'll return the object at the given position (index).
In your case, it'd be the yourList.get(0).
List#remove() will help:
List<String> cards = new ArrayList<>();
for (char suit : "♥♦♠♣".toCharArray())
for (char rank : "23456789TJQKA".toCharArray())
cards.add(String.valueOf(rank) + String.valueOf(suit));
Collections.shuffle(cards);
System.out.println(cards.remove(0)); // Q♥ //
Related
Ok so, I have a fillhand method that is supposed to get cards from a shuffled deck and add the cards one by one through the top method while also sorting them by suits. The top method saves the card at shuffledDeck at index 0 to a variable, removes the index at 0, and then returns the card. So i added the first card, then its suppose to check if the next card that top returns is of a different suit, if it is then add it to the array list, if it is of the same suit then add it to the arraylist but, in order of ranks within that suit. As of now, where it is supposed to check if the handArray contains the upcoming card's suit == false is not working.
public ArrayList fillHand(ArrayList Array, int handSize)
{
ArrayList<Card> shuffledDeck = Array;
handArray.add(deck.top(shuffledDeck));
for (int i = 0; i < handSize + 1; i++)
{
if (handArray.contains(shuffledDeck.get(i).getSuit()) == false)
{
handArray.add(deck.top(shuffledDeck));
}
}
return handArray;
}
Since you didn't post any code, I'll assume that Deck is a class with two attributes(rank and suit).
You'll want to create a method for this class that makes it print itself(i.e. "Ace of Spades" or "Jack of Hearts")
You'll also need a method that returns the suit.
From there you iterate over your arraylist and call that method on each node that satisfies the required suit
Edit, since code was posted:
The logic itself seems flawed, you're iterating over the handSize, checking if the suit number is in the handArray. This is a major issue, as handArray is an array of Card, not an array of int.
There are multiple ways to fix this, the simpler ones are:
Simplest: iterate over the handArray manually, checking if the suit matches with any of the card's
Faster: creating an array of size 4, with all values initialized as false, representing whether or not a suit is in the handArray.
Now that the if statement is dealt with, we must fix it's code. As of now, you're checking if the i suit is in the Array, and adding the top card to it.
The best course of action here would be ditching the for loop, replacing it with something like this:
while(ArrayList.size()){
/* code */
}
This will loop the array due to the way that top works, since it removes the top card
I am creating a simplistic poker game in Java that will create a deck of cards, let you draw a hand and display what kind of suit you have. Here is what I have so far and have run into a problem.
I have 3 different Array Lists, one for the card values, one for the card suits, and one to hold the actual card objects once the card suit and value is applied. I created a loop that is supposed to add a suit to each value (13 values) and add them into the newCards ArrayList (it is of type CARD, a different class I have that allows the objects to have both an integer and a string). After I try to print out newCards to see if it works properly. I get quite a few exception errors.
I'm not sure how to efficiently create a loop like this so any help is appreciated.
import java.util.*;
public class pokerMain {
public static void main (String [] args){
ArrayList<String> suits = new ArrayList<String>();//array list for the card suits
ArrayList<Integer> val = new ArrayList<Integer>();//array list for card values
ArrayList<CARDS> newCards = new ArrayList<CARDS>();//array list for cards with assigned val/suits
suits.add("Clubs");//These are the suits, added to the suits ArrayList
suits.add("Hearts");
suits.add("Diamonds");
suits.add("Spades");
System.out.println("suits contains: " + suits );//Testing for suit
for(int i = 1; i <= 13; i ++){//loop that adds all 13 values to to the val ArrayList
val.add(i);
}
System.out.println("val contains " + val);//Testing for val
This is the loop
for(int i = 0; i <= val.size(); i ++){//This loop will be used to add a suit to every card value
newCards.add(new CARDS(suits.get(0), val.get(i)));//assigns hearts
newCards.add(new CARDS(suits.get(1), val.get(i)));//assigns hearts
newCards.add(new CARDS(suits.get(2), val.get(i)));//assigns diamonds
newCards.add(new CARDS(suits.get(3), val.get(i)));//assigns spades
}
-------------------------------------------------------------------------
System.out.println(newCards.toString());//prints newCards arrayList
//newCards.add(card);// puts card object into array list newCards
To prevent code duplication you could try two loops and use for each
for(String s : suits) {
for(Integer i : val) {
newCards.add(new CARDS(s, i));
}
}
Firstly, as John Mercier said, for:each is the way to go here.
Secondly, and this isn't causing your problem, but CARDS is not exactly a conventional class name. Something like Card or Cards (or wrap the Card in a Deck class...).
Thirdly, and most importantly, the main() doesn't seem to be your problem, as far as I can tell. Check your CARDS class.
This question already has answers here:
How to remove specific element from an array [duplicate]
(6 answers)
Closed 8 years ago.
public class Example {
public static void main(String [] args) {
String [] wombology;
wombology = new String[3];
wombology[0] = "History of Wombology";
wombology[1] = "Why Wombology";
wombology[2] = "Wombology and Me";
Random book = new Random(System.currentTimeMillis());
Scanner choice = new Scanner(System.in);
String yourChoice;
do {
System.out.println("Press enter for random book");
yourChoice = choice.nextLine();
if(yourChoice.equals("")) {
System.out.println(wombology[randomizer.nextInt(3)]);
System.out.println();
}
if(yourChoice == "EXIT") {
break;
}
} while(!yourChoice.equals("EXIT"));
}
}
How could I take out a "book" from the array once chosen randomly?
How could I put back in said "book" later back into the array?
Example: "History of Wombology" is randomly chosen and is taken out.
The next random selection should NOT include "History of Wombology" until it is put back in.
Meaning only "Why Wombology" and "Wombology and Me" should be the only possible choices.
I'm assuming that this is homework and an ArrayList is not possible. And I don't want to give a full, detailed answer.
One option might be to create a parallel array, boolean isCheckedOut[], and track your books there.
You need to manage the array yourself. That means you need to know the real size of the array and the filled size. This is because once the array is created the size cannot change.
If you delete an object from the array you need to shift the adjacent elements towards that position.
For example, your array looks like this:
[A|B|C|D|E|F]
allocatedArraySize = 6
currentSize = 6
If you delete C which is at position 2 then you must shift D, E, F to the left. You could also make the last position null.
[A|B|D|E|F|null]
allocatedArraySize = 6
currentSize = 5
To insert, simply use this:
// Check Array is not full.
if(currentSize != allocatedArraySize)
{
// Then add your object to the last position in the array.
array[currentSize] = obj;
// Increment the index.
currentSize++;
}
else
{
// Don't allow insertion.
// Or create a new-bigger-array;
// then copy all elements of the full array into it.
}
You have to "define" an action for "taking out a book" on the technical level. I can image two possibilities for this
setting the array content at the specific position to null
setting the array content at the specific position to an empty string
As the title of most books consists of one or more letters, the empty string-proposal seems also to be valid.
The second task (putting a book back into the array) can be handled in a similar way. Here you have to find an empty place (an array position with an empty string/null as content) and assign the name of the book to it.
Concerning the randomizer and not allowing already removed books: you can use the aforementioned condition to rerun the randomizer, i.e until an non-empty string/not-null element is found in the array. If you found one, it is a valid choice. But beware, if you removed all books, the randomizer would never stop running (because it finds only invalid choices and hence never returns). Here you can use an additional check condition: if the array only consists of empty strings/ null values, it is not required to run the randomizer.
Hope that helps...
I'm new to Java and I am having trouble wrapping my mind around one of the concepts.
The assignment I am currently working on is the card game War. The current instructions is for me to remove a random card from a a deck of cards.
I have created an array, but it is an array of class Card. The class creates the card by basically adding an int and a String together. I then created the array from that class. In my mind, I neither have an int or a String in my array, is that correct?
Now I need to remove one of the random cards from the deck and give it to a player. This is where I am getting lost. I would think I can just use Random to remove a random card, but I always seem to get an error.
I'm not asking for you to do the assignment for me, but if you would please point me in the right direction and possibly correct me if I am confused.
Current Class I am working on:
import java.util.Random;
import java.util.*;
public class War3
{
Random ran = new Random();
public FullDeck randomCard()
{
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
int index = ran.nextInt(randCard.size());
FullDeck x = randCard.remove(index);
return x;
}
public void display()
{
System.out.println("Your card is" + randomCard());
}
}
Entire project for clarification Java - War Game - Gist
Many thanks in advance.
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
This creates an ArrayList. You do not need to specify the number 52, since ArrayLists grow dynamically, as opposed to Arrays. The call is similar to
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> ();, the difference being that the constructor you used sets the initial capacity of the ArrayList to 52. That in no way restricts the size of the ArrayList though.
Anyway, you are creating a new, empty ArrayList. Then you want the size, but since you didn't put anything into the list, it is still empty, to the size is zero. You then try to call ran.nextInt(0)... nextInt(int n) expects a number greater than zero. From the javadoc:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
Two issues that I see:
You're creating an ArrayList that can hold a reference to 52 instances of the FullDeck class, but you're not adding anything to it. You need to do something like randCard.add(new FullDeck()) 52 times/in a loop**. Then likely you'll want to "shuffle" the deck, see this question for how to do that.
You're naming is a little weird...the FullDeck class in actuality seems like it should be renamed to just Card, and the randCard variable should be renamed to something like fullDeck...after you've added 52 Cards.
**EDIT: actually, the generation of a deck of cards will be more complicated to make sure you don't have any duplicate cards.
Disclaimer: This is for a homework assignment.
I am currently working on an assignment where I need to implement an iterable interface in order to pass each array from a square two-dimensional array. This array is supposed to represent a grid of numbers (so I will be referring to them as such [row][col]). My problem is that I want to use the same next method to iterate through the rows and the columns. First, is this possible? Second, any suggestions/hints?
My next method currently looks like this:
public Data[] next(){
Data [] holder = new Data[ray.length];
for (int i = 0; i <ray.length; i++)
holder[i]=ray[counter][i];
counter++;
return holder;}
EDIT: I am aware of being able to switch counter and i in ray[counter][i], but I'm not sure how to have it do both if that's possible.
ray is the multidimensional array and count is an attribute of the Iterator method I've created (It's initialized to 0 and this is the only method that changes it). I know I cannot return the "column" of ray this way, so how would I go about having next call columns and rows?? Thanks for any of the help. I'll be standing by if you have further questions.
My problem is that I want to use the same next method to iterate through the rows and the columns. First, is this possible?
Yes it is possible, assuming you mean what I think you mean. (The phrase "iterate through the rows and the columns" is horribly ambiguous.)
Since this is a homework exercise here are a couple of hints:
You need two counters not one.
When you get to the end of one row you need to go to the start of the next row. (Obviously!) Think about what that means if you've got two counters.
This should be enough to get you on the right track.
I want a row by row iteration and a column by column iteration.
This is also a horribly ambiguous description, but I'm going to interpret it as meaning that sometimes you want to iterate left to right and top to bottom, and other times you want to iterate top to bottom and left to right.
That is also possible:
One possibility is to use an extra state variable to tell the iterator which direction you are iterating; i.e. row within column, or column within row.
Another possibility is to implement two distinct Iterator classes for the two directions.
The problem is that the iterator class is only supposed to have one counter and returns an single-dimension array.
You've (finally) told us unambiguously that the iterator is supposed to return an array. (A good dentist could pull out a tooth quicker than that!)
So here's a hint:
Returning the ith row is easy, but returning the jth column requires you to create a new array to hold the values in that column.
My advice is: transform the 2d array to a list and iterate.
When initialize the Iterator, transform the list. Then you could iterate the list easily.
Following is p-code, you could enrich the implementation in your homework. Hope it helps you!
class TwoDimeIterator implements Iterator<Date> {
List transformedList = new ArrayList();
int cursor = 0;
/** transform to a list row by row.
So you could define your Iterator order.**/
TwoDimeIterator(){
for(int i=0; i < ray.length; i++)
for(int j=0; j < ray[0].length; j++)
transformedList.add(ray[i][j]);
}
public Date next() {
return transformedList.get(cursor++);
}
public boolean hasNext() {
return cursor != transformedList.size();
}
//...
}