簡體   English   中英

印刷賓果板,Java

[英]Printing Bingo Board, 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);

    }

}

您不會在每次使用之間更改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
}

一旦您開始使用循環來打印每一行,您將遇到的問題是無法保證您不會得到重復的數字,而這對 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM