在Java中,我們可以方便地計(jì)算一副撲克牌的點(diǎn)數(shù)和。首先,我們需要定義每個(gè)牌面對應(yīng)的點(diǎn)數(shù),例如:A為1點(diǎn),J、Q、K為10點(diǎn),其他牌面對應(yīng)相應(yīng)的數(shù)字點(diǎn)數(shù)。
//定義牌面點(diǎn)數(shù) int[] points = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
接著,我們需要生成一副有52張牌的撲克牌,并將其隨機(jī)洗牌,代碼如下:
//生成一副撲克牌 List<Integer> deck = new ArrayList<>(); for(int i = 0; i < 4; i++){ for(int j = 1; j <= 13; j++){ deck.add(j); } } //將牌堆隨機(jī)洗牌 Collections.shuffle(deck);
接下來,我們可以對牌堆進(jìn)行抽牌,并將牌面點(diǎn)數(shù)累加到總點(diǎn)數(shù)中:
//從牌堆中抽取5張牌 List<Integer> hand = deck.subList(0, 5); //計(jì)算手牌點(diǎn)數(shù)和 int sum = 0; for(int card : hand){ sum += points[card]; }
最后,我們可以輸出手牌總點(diǎn)數(shù)以及牌堆中剩余的牌:
System.out.println("手牌點(diǎn)數(shù)和為:" + sum); System.out.println("牌堆中剩余的牌為:" + deck.subList(5, deck.size()));
這樣,我們就完成了一副撲克牌的點(diǎn)數(shù)和計(jì)算。完整代碼如下:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CardGame { public static void main(String[] args) { //定義牌面點(diǎn)數(shù) int[] points = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10}; //生成一副撲克牌 List<Integer> deck = new ArrayList<>(); for(int i = 0; i < 4; i++){ for(int j = 1; j <= 13; j++){ deck.add(j); } } //將牌堆隨機(jī)洗牌 Collections.shuffle(deck); //從牌堆中抽取5張牌 List<Integer> hand = deck.subList(0, 5); //計(jì)算手牌點(diǎn)數(shù)和 int sum = 0; for(int card : hand){ sum += points[card]; } //輸出結(jié)果 System.out.println("手牌點(diǎn)數(shù)和為:" + sum); System.out.println("牌堆中剩余的牌為:" + deck.subList(5, deck.size())); } }