简体   繁体   English

Java在for循环中生成随机数

[英]Java Generating random numbers in a for loop

I'm creating a blackjack program and am trying to deal random cards to the players at the beginning of the program. 我正在创建一个二十一点程序,并试图在程序开始时向玩家随机发牌。 This is the function I have written in Java to initially deal cards to players. 这是我用Java编写的用于最初向玩家发牌的功能。

public static int[][] initDeal(int NPlayers)
    {
        int hands[][] = new int[NPlayers][2];

        for(int a = 0; a<NPlayers; a++)
        {

            hands[a][0] = (int)Math.round((Math.random() * 13))-1;
            hands[a][1] = (int)Math.round((Math.random() * 13))-1;

        }
        return hands;
    }

I think there is a problem with the Random method and the for loop as although the two cards for each player are being generated randomly, all players are dealt the same cards. 我认为Random方法和for循环存在问题,因为尽管每个玩家的两张牌都是随机生成的,但所有玩家都被分配了相同的牌。

You need to have a 'Deck' of cards or somesuch, and randomly shuffle them, and then deal them out to Players by removing them from the Deck. 您需要有一张“牌组”牌或类似的牌,然后随机洗牌,然后通过将其从牌组中取出来分发给玩家。

Otherwise you can deal the same card twice, which is not possible in real life. 否则,您可以两次发行同一张卡,这在现实生活中是不可能的。 (Though larger decks can be used.) (尽管可以使用更大的甲板。)

public class Card {
    public enum Suit {HEART, DIAMOND, CLUB, SPADE};
    public int getValue();         // Ace, Jack, Queen, King encoded as numbers also.
}

public class Deck {
    protected List<Card> cardList = new ArrayList();

    public void newDeck() {
       // clear & add 52 cards..
       Collections.shuffle( cardList);
    }
    public Card deal() {
        Card card = cardList.remove(0);
        return card;
    }
}

If/when you do need to generate random integers, you should use truncation , not rounding. 如果确实需要生成随机整数,则应使用截断而不是舍入。 Otherwise the bottom value will have only half its desired probability.. 否则,最低值将只有其所需概率的一半。

int y = Math.round( x)
0   - 0.49   ->    0         // only half the probability of occurrence!
0.5 - 1.49   ->    1
1.5 - 2.49   ->    2
..

There's no Math function to truncate, just cast to int . 没有要截断的Math函数,只是强制转换为int

int faceValue = (int) ((Math.random() * 13)) + 1;

Or, you can use the Random.nextInt( n) function to do this. 或者,您可以使用Random.nextInt(n)函数执行此操作。

Random rand = new Random();
int faceValue = rand.nextInt( 13) + 1;

Fill in the blanks. 填写空白。

Try using the nextInt(n) of the class java.util.Random . 尝试使用java.util.Random类的nextInt(n) Where n = 13 . 其中n = 13 But by the looks of it, the problem seems to be elsewhere. 但是从外观上看,问题似乎出在其他地方。 The function is indeed returning random values but you are not using it properly somewhere else. 该函数确实返回了随机值,但是您在其他地方没有正确使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM