gpt4 book ai didi

java - 如何计算牌值在一副牌中出现的次数

转载 作者:行者123 更新时间:2023-12-01 09:21:24 25 4
gpt4 key购买 nike

我正在尝试找到一种方法来计算牌值在一副牌中出现的次数。我已经为 Card 和 DeckHand 创建了类。在 DeckHand 类中,我尝试创建一个方法,允许用户选择要搜索和计数的卡值。我尝试过几种不同的方法,但似乎没有任何效果。有什么想法吗?

卡片类别:

class Card {
private int _value, _suit;
private String[] _cardValues = {null, "Ace", "2", "3", "4","5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
private String[] _cardSuits = {null, "Clubs", "Diamonds", "Hearts", "Spades"};

public Card(int value,int suit) {
_value = value;
_suit = suit;
}
public int getCardValue() {
return _value;
}
public int getCardSuit() {
return _suit;
}
public String toString() {
return _cardValues[_value] + " of " + _cardSuits[_suit];
}

}甲板等级:

class DeckHand{
private Card[] _deckHand;
private int _deckSize;
private static final int MAXSIZE = 52;
private Card[] newDeck;

public DeckHand() {
_deckHand = new Card[MAXSIZE];
_deckSize = 0;
}
public DeckHand(int deckSize) {
_deckHand = new Card[MAXSIZE];
int index = 0;
for (int suit = 1; suit <= 4; suit++) {
for (int rank = 1; rank <= 13; rank++) {
_deckHand[index] = new Card(rank, suit);
index++;
}
}
_deckSize = deckSize;
}
public int count(int value){
int count = 0;
for (int i = 0; i<=_deckSize; i++) {
if(_deckHand[i].getCardValue()==value)
count++;
}
return count;
}
}

主要:

public class Program4 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
int suit, value;
DeckHand standard = new DeckHand(52);
System.out.println("\nWhich card value would you like to count?");
String[] values = {null, "Ace", "2", "3", "4","5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
System.out.println("Card Value Options: "
+ "\n-------------------");
for(int i = 1;i<values.length; i++) {
System.out.println(i + " - " + values[i]);
}
System.out.print("\tOption: ");
value = keyboard.nextInt();
System.out.println("---------------------------"
+ "-----------------------------\n"
+ "The card value " + value appears " + standard.count(value)
+ " times in the deck."
}

我试图让程序要求用户在卡片数组中选择一个值并计算该卡片值出现的次数(即 2 或 5),然后将该数字输出到用户(即“该卡牌值在牌组中出现了这次数”)。但是,当我尝试运行此命令时,我得到的只是“该卡牌值在牌组中出现 0 次”,或者收到一条错误消息,指出此行有问题:

if(_deckHand[i].getCardValue()==value)

这是错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 52
at program4.DeckHand.count(Program4.java:231)
at program4.Program4.main(Program4.java:101)
C:\Users\alisa_000\AppData\Local\NetBeans\Cache\8.1\executor-
snippets\run.xml:53: Java returned: 1

最佳答案

异常是由 for 循环引起的:它运行 0 到 52(含)。您的卡片数组的最大大小为 52,这意味着它包含从 0-51(52 个值)的卡片。当您尝试访问索引 52 处的卡时,您会收到一个 indexArrayOutOfBoumdsException,因为它根本不存在。 Indtead 你应该改变你的 for 循环:

for(int i = 0;i<=_deckSize;i++){

致:

for(int i = 0;i<_deckSize;i++){

请注意“=”如何消失,现在它永远不会访问索引 52 或这副牌中的第 53 张牌。

关于java - 如何计算牌值在一副牌中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com