I am trying to make text based blackjack game. I already made :
- Card class which create new card based on integer
- Deck class which consists of Deck LinkedList populated by Card.

I also made 2 new LinkedLists for gambler and dealer. I already managed to remove elements from a shuffled Deck and add them to the new Lists using

gambler.addFirst(myApp.cards.removeFirst());

However I am stumped on how to count the total of the elements inside gambler and dealer without removing them. If I used peek() method, it only take the head of the lists.

Any help is appreciated.

doel

Recommended Answers

All 4 Replies

tried to just run the list trough a loop and add the value of every element to a seperate counter?

If you are using the Java Collections LinkedList class, you can use the size() method to determine the number of elements in the list.

I am wondering though, why not use a different collection to hold the cards? Would a Vector of ArrayList work just as well? Is there a compelling reason you are using LinkedList? You should examine your usage of a collection of objects and choose the collection implementation based upon your needs.

I an a newbie at Java so I don't know much about Vector of ArrayList. Anyway I solved it by creating a temp LinkedList. I don't know if it's the most effective solution......

[B]public [/B][B]static [/B][B]int[/B] countCards(LinkedList<Card> content){
[B]int[/B] total = 0;
LinkedList<Card> temp = [B]new[/B] LinkedList<Card>();
temp = content;
 
[B]while[/B] (!temp.isEmpty()){
total += temp.removeFirst().rank();
}
 
[B]return[/B] total;
}

Thanks again for all input.

I an a newbie at Java so I don't know much about Vector of ArrayList.

Ah, sorry that was a typo that shoud have read Vector or ArrayList. They are merely array-backed collections of objects that provide for iteration and also random access (insertion, removal, retrieval).

Anyway I solved it by creating a temp LinkedList. I don't know if it's the most effective solution......

[B]public [/B][B]static [/B][B]int[/B] countCards(LinkedList<Card> content){
[B]int[/B] total = 0;
LinkedList<Card> temp = [B]new[/B] LinkedList<Card>();
temp = content;
 
[B]while[/B] (!temp.isEmpty()){
total += temp.removeFirst().rank();
}
 
[B]return[/B] total;
}

Thanks again for all input.

You don't really need to remove from the list just to examine things in the list. You can simply iterate the collection with a "for each" loop, so your example code becomes:

[B]public [/B][B]static [/B][B]int[/B] countCards(LinkedList<Card> content){
[B]int[/B] total = 0;
for (Card card : content){
  total += card.rank();
}
 
[B]return[/B] total;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.