In a package called “bag”, create a class called MyBag that implements the Bag i
ID: 3873435 • Letter: I
Question
In a package called “bag”, create a class called MyBag that implements the Bag interface:
-}
- Your MyBag implementation should use the Java ArrayList as its underlying data structure.
Any change made to the Bag interface or using a data structure/implementation other than
an ArrayList will result in a grade of 0. If you have any questions, ask!
Create a new class called BagHand in the cards package from the Activity which implements
the HandOfCards interface using your MyBag class. The BagHand class should contain a method called getValue() that returns the value of the hand using Blackjack rules (you can assume the value of an Ace is always 11).
Explanation / Answer
Bag.java:
public interface Bag<T> extends Iterable<T> {
public boolean isEmpty();
public int size();
public void add(T item);
}
MyBag.java:
import java.util.ArrayList;
import java.util.Iterator;
public class MyBag<T> implements Bag<T>{
ArrayList<T> list = new ArrayList<>();
@Override
public boolean isEmpty() {
return list.isEmpty();
}
@Override
public int size() {
return list.size();
}
@Override
public void add(T item) {
list.add(item);
}
@Override
public Iterator<T> iterator() {
return list.iterator();
}
}
Card.java:
public class Card {
private String suit;
private int value;
public Card(String s, int v) {
suit = s;
value = v;
}
@Override
public String toString() {
String[] sVal = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack",
"Queen", "King"};
return sVal[value] + " of " + suit;
}
// Assuming value contains the index as per sequence:
// { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}
// Ace has value 11, Face cards value 10, other as per their rank
public int getVal() {
switch(value) {
case 0:
return 11;
case 10:
case 11:
case 12:
return 10;
default:
return value + 1;
}
}
public String getSuit() {
return suit;
}
}
BagHand.java:
import java.util.Iterator;
public class BagHand {
Bag<Card> hand = new MyBag<>();
public void addCard(Card c) {
hand.add(c);
}
public int getValue() {
int value = 0;
Iterator<Card> iterator = hand.iterator();
while(iterator.hasNext()) {
Card c = iterator.next();
value += c.getVal();
}
return value;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.