gpt4 book ai didi

java - 通过/返回不起作用

转载 作者:行者123 更新时间:2023-11-29 10:11:59 25 4
gpt4 key购买 nike

public class BlackJack {

static String[] deck = new String[52];

//Creates Deck of cards
public static void main (String[] args) {
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace" };

for (int a=0; a < rank.length; a++) {
for (int b=0; b < suit.length; b++){
deck[suit.length*a + b] = (rank[a] +" of "+ suit[b]);
}
}

//Trying to get this to print out the returned card name
String card = "G";
randomCard(card);
System.out.println(card);
}

//Pulls a random card from the deck
public static String randomCard(String cardName) {
//Generates a random number between 0 and 52
int card = (int)(Math.random()*53);
cardName = (deck[card]);
return cardName;

}

}

所以我的 main 方法的第一部分生成了一副纸牌并且工作得很好(我已经单独测试过)。我正在尝试让我的第二种方法 randomCard 从牌组中返回一张随机抽取的牌。我只能让它打印出“G”,我可以测试它是否正常工作。帮助将不胜感激。谢谢!

最佳答案

您需要对返回值进行赋值。

card = randomCard(card);

在方法 cardName = deck[card]; 内部进行的赋值仅更新方法本地 String 引用 cardName 并且在外部没有任何影响方法的范围。

另请参阅 Collections.shuffle() 以更好的方式随机分发卡片。 .阅读this blog entrythis one有关洗牌的更多信息。

ArrayList<String> deck = new ArrayList<String>();

String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King", "Ace" };

for (int a=0; a < rank.length; a++) {
for (int b=0; b < suit.length; b++){
deck.add(rank[a] +" of "+ suit[b]);
}
}

Collections.shuffle(deck, new SecureRandom());
String randomCard = deck.get(0);

关于java - 通过/返回不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30018570/

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