印刷宾果板,Java

时间:2018-10-03 00:33:26

标签: java

所以我试图用随机数打印宾果游戏板。每当我运行此命令时,我都会在列中得到相同的数字。如何使每一行打印不同的数字?

import java.util.Random;

public class Bingo {

public static void main(String[] args) {
        Random rand = new Random();
        int bLow = 0, iLow = 16, nLow = 44, gLow = 59, oLow = 74;
        int bLimit = 15, iLimit = 30, nLimit = 45, gLimit = 60, oLimit = 75;
        int rB = rand.nextInt(bLimit-bLow) + bLow, rI = rand.nextInt(iLimit-iLow) + 
iLow, rN = rand.nextInt(nLimit-nLow) + nLow, rG = rand.nextInt(gLimit-gLow) + gLow, 
rO = rand.nextInt(oLimit-oLow) + oLow;
        System.out.println("B\t|\tI\t|\tN\t|\tG\t|\tO");
        System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + 
"\t|\t" + rO);
        System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + 
"\t|\t" + rO);
        System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + 
"\t|\t" + rO);
        System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + 
"\t|\t" + rO);
        System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + 
"\t|\t" + rO);

    }

}

2 个答案:

答案 0 :(得分:0)

您不会在每次使用之间更改rB的值。考虑使用循环。

for (int i = 0; i < 5; i++) {

   int rB = rand.nextInt(bLimit-bLow) + bLow; // etc

   System.out.println(rB + "\t|\t" + rI + "\t|\t" + rN + "\t|\t" + rG + "\t|\t" + rO);  // etc
}

答案 1 :(得分:0)

一旦开始使用循环来打印每一行,您将遇到的问题是无法保证您不会得到重复的数字,而这对于Bingo来说是不会的!

您可以改为执行以下操作-为每列创建有效数字列表,并使用Collections.shuffle对其随机化。

List<List<Integer>> board = new ArrayList<>();
for(int i=0, low=0; i<5; i++, low+=15)
{
  List<Integer> col = new ArrayList<>();
  board.add(col);
  for(int j=1; j<=15; j++) col.add(low+j);
  Collections.shuffle(col);
}

System.out.println("B\t|\tI\t|\tN\t|\tG\t|\tO");
for(int row=0; row<5; row++)
{
  for(int col=0; col<5; col++)
  {
    System.out.printf("%2d", board.get(col).get(row));
    if(col<4) System.out.printf("\t|\t");
  }
  System.out.println();
}

输出:

B   |   I   |   N   |   G   |   O
14  |   26  |   40  |   46  |   74
 2  |   20  |   42  |   52  |   73
11  |   25  |   43  |   47  |   64
 7  |   19  |   33  |   56  |   61
 3  |   30  |   36  |   60  |   68