Java在for循环中生成随机数

问题描述:

我正在创建一个二十一点程序,并试图在程序开始时向玩家发送随机卡。这是我用Java编写的函数,用于向玩家初始交易牌。Java在for循环中生成随机数

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; 
    } 

我认为这是与随机方法的问题,并在for循环中,虽然被随机生成的两个卡每个球员,所有球员都处理相同的牌。

+0

你的问题是什么? – Masudul

+0

如果我是你,我会换出你的多维数组以获得一个“Hand”对象的列表或数组。将使它更清洁。 – christopher

+0

为什么不使用java.util.Random.nextInt(13)'? – Mureinik

你需要有一副牌或者某些东西,然后随机洗牌,然后把它们从甲板上移走,交给玩家。

否则,您可以处理同一张卡片两次,这在现实生活中是不可能的。 (虽然较大的甲板可以使用。)

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; 
    } 
} 

如果/当你需要生成随机整数,你应该使用截断,而不是四舍五入。否则,底部值将只有一半的期望概率..

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 
.. 

有没有Math函数来截断,只投给int

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

或者,您可以使用Random.nextInt(n)函数来执行此操作。

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

填空。

尝试使用类java.util.RandomnextInt(n)。其中n = 13。但从外观上看,问题似乎在别处。该函数确实返回了随机值,但您没有在其他地方正确使用它。