Reputation: 73
I am a Java beginner and trying to get a console blackjack to run. I created an ArrayList with cards as Strings, such as "3 Spades". Now I need to check for the values so that I dont get more than 21 for example. I have tried giving all of the Strings ints but it that isnt working for me. Is there a way to filter only the numbers out of the String and save as an int? Thanks for your help.
public ArrayList<String> Karten () {
ArrayList<String>Herz = new ArrayList<String>(
Arrays.asList(" 2 Herz "," 3 Herz "," 4 Herz "," 5 Herz "," 6 Herz "," 7 Herz "," 8 Herz "," 9 Herz "," 10 Herz ", " Bube Herz ", " Dame Herz ", " König Herz ", " Ass Herz "));
Upvotes: 1
Views: 162
Reputation: 4475
You can also create a new type Card which has a numeric value field:
public class Card {
private int value;
private String valueLabel;
private String shape;
public Card(int value, String valueLabel, String shape) {
this.value=value;
this.valueLabel=valueLabel;
this.shape=shape;
}
public int getValue() {
return value;
}
public String toString() {
return valueLabel+" "+shape;
}
}
This also solves your problem for " Bube Herz ", " Dame Herz ", " König Herz ", " Ass Herz " which don't have a number.
Now you can build your hand as a list of Card instances:
ArrayList<Card> cards=new ArrayList<>(Arrays.<Card>asList(new Card(1,"Ass","Herz"), new Card(2,"2","Herz")));
int totalValue=cards.stream().mapToInt(c->c.getValue()).sum();
System.out.println("Your hand:"+cards);
System.out.println("has a total value of:"+totalValue);
Output:
Your hand:[Ass Herz, 2 Herz]
has a total value of:3
Upvotes: 2
Reputation: 809
When you get a card, try the following:
String card = "3 Spades"
String[] cardSplit = str.split(" ");
int cardValue = Integer.parseInt(cardSplit[0]);
String cardType = cardSplit[1];
You can now use cardValue
as an integer and add it to a total. You can also reference cardType
if you need the type of card, but assuming this is Black Jack I don't think it matters much.
Let me know if this helps.
Upvotes: 2