我有点像Java新手,所以我要学习Java类。我正在处理当前的作业,该作业要求我创建一个类,其中包含Card类型(锹,菱形等)及其编号(1、2、3 Jack等)的数据类型。我已经设法解决了这个问题,但是我被要求让班级随机产生这些数字,以便从甲板上随机选择一张卡片。以下是我目前用于卡片类的代码。
table tr {
display:flex;
flex-direction: column;
float: left;
}
thead,tbody {
float: left;
}
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;
}}
TestCard类是我目前拥有的类,但是我试图用随机分配的值(等级1-4,适合1-13)替换内部的值。那么如何从Card类的数组中生成一个随机值,然后在TestCard类中调用它呢?
答案 0 :(得分:1)
下面是一段代码,可以帮助您入门:
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 Clubs
如果您不想选择null:
String randomRank = ranks[random.nextInt(ranks.length - 1) + 1];
String randomSuit = suits[random.nextInt(suits.length - 1) + 1];
答案 1 :(得分:0)
首先,将“ null”作为数组中的第0个元素是错误的形式(在Java和所有其他0-index语言中)。您需要放心,计数从零开始-因为您在Java Universe中会遇到的所有其他代码都将基于该假设。
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
基本上,您的问题将减少为产生一对随机数。 0-4中的第一个,包括0但不包括4,0-14中的第二个,包括0但不包括14。
幸运的是,Java提供了这样的功能Random.nextInt(int bound)
。您将按以下方式使用它:
Random r = new Random();
int suite = r.nextInt(4);
int rank = r.nextInt(14);
您可以了解有关该方法https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#nextInt-int-