我是一个java新手,所以我正在学习java类(class)。我正在完成当前的作业,要求我创建一个类来保存卡片类型(黑桃、钻石等)的数据类型及其数字(1、2、3 jack 等)。我已经设法解决了这个问题,但我被要求让全类随机生成这些数字,以便从牌堆中随机选择一张牌。以下是我的卡片类的当前代码。
public class Card {
private int rank, suit;
public Card(int rank, int suit) {
this.rank = rank; //set methods
this.suit = suit;
}
public String toString(){
String[] suits = {null, "Clubs", "Diamonds", "Hearts", "Spades"}; //Null is never used, replaces 0
String[] ranks = {null, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; //Null is never used, replaces 0
String drawnCard = ranks[this.rank] + " of " + suits[this.suit];
return drawnCard;
}}
class TestCard
{
public static void main (String args[]){
Card card = new Card(8, 4);
{
System.out.println(card);
}
}
}
TestCard 类是我目前拥有的类,但我正在尝试用随机分配的值(排名 1-4,套装 1-13)替换其中的值。那么如何从 Card 类中的数组生成随机值并在 TestCard 类中调用它呢?
最佳答案
这里有一段代码可以帮助您入门:
public static void main(String[] args) {
String[] suits = {null, "Clubs", "Diamonds", "Hearts", "Spades"}; //Null is never used, replaces 0
String[] ranks = {null, "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; //Null is never used, replaces 0
Random random = new Random();
String randomRank = ranks[random.nextInt(ranks.length)];
String randomSuit = suits[random.nextInt(suits.length)];
System.out.println(randomRank + " " + randomSuit);
}
输出示例:6 个俱乐部
如果您不想选择 null:
String randomRank = ranks[random.nextInt(ranks.length - 1) + 1];
String randomSuit = suits[random.nextInt(suits.length - 1) + 1];
关于java - 如何为类(class)生成随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58291643/