Reputation: 21
I am having an issue with my scoring in my blackjack game. It works in finding the right score, but when the user draws a new card it will incorrectly add the score.
For example: Orginial hand is : 4 and 5 (so score 9) User draws a 10. Instead of score being 19 is will instaed be 19+9 or 28.
Here is my code: Scoring method:
public int getHandValue() {
boolean ace = false;
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
points += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
points += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
points += 11;
}
}
return points;
}
Play method:
public void play(Deck deck) {
boolean isDone = false;
if (this.getHandValue() > 21){
System.out.println("You have busted!");
isDone = true;
this.lose();
}
takeCard(deck.drawCard());
takeCard(deck.drawCard());
System.out.println("Here are your cards and your score:");
System.out.println(this.hand.toString());
System.out.println("Score: " + getHandValue());
ListItemInput hitOrPass = new ListItemInput();
hitOrPass.add("h", "hit");
hitOrPass.add("p", "pass");
while (!isDone){
System.out.println("Hit or pass?");
hitOrPass.run();
if (hitOrPass.getKey().equalsIgnoreCase("h")) {
String result = "";
this.takeCard(deck.drawCard());
result += "You hand is now " + this.hand.toString() + "\n";
result += "Your score is now " + this.getHandValue();
System.out.println(result);
} else {
System.out.println("You have chosen to pass.");
isDone = true;
}
}
}
Upvotes: 0
Views: 133
Reputation: 4089
You loop over the hand each time you call your method so your points should reset before doing so. Otherwise the points increase by 2x + the extra card in the hand. Reset the value before you loop your hand
public int getHandValue() {
boolean ace = false;
points = 0; //<--- reset the point total
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
points += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
points += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
points += 11;
}
}
return points;
Upvotes: 1
Reputation: 1913
I assume points
is being declared outside of this method.
Since you are returning points it is best not to use a class-wide variable for this. You'll end up with unexpected results like this. Instead, use variable within the method scope, like this.
public int getHandValue() {
boolean ace = false;
int value = 0;
for (int i = 0; i < this.hand.size(); i++) {
if (this.hand.get(i).getRank().value > 10) {
value += 10;
} else if (this.hand.get(i).getRank().value == 1) {
ace = true;
} else {
value += this.hand.get(i).getRank().value;
}
if (ace == true && points + 11 <= 21) {
value += 11;
}
}
return value;
}
Upvotes: 0