上届世界杯_世界杯韩国 - cngkpt.com

Java 中的骰子游戲

本教程將演示一個用 Java 建立簡單骰子游戲的程式。

為此,我們將使用 java.util.Random 包生成 1 到 6 之間的隨機數,代表骰子上的數字。在我們的示例中,我們將模擬 N 個擲骰子的人。我們將丟擲 N 個骰子,我們將新增並列印其結果。

我們可以以此程式為基礎設計各種其他骰子游戲。

請參考下面給出的程式碼。

import java.util.Random;

import java.util.Scanner;

public class Main {

public static void main(String args[]) {

System.out.print("Enter the number of dice: ");

Scanner input = new Scanner(System.in);

int numberOfDice = input.nextInt();

Random ranNum = new Random();

System.out.print("Hey Coder! You rolled: ");

int total = 0;

int randomNumber = 0;

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

randomNumber = ranNum.nextInt(6) + 1;

total = total + randomNumber;

System.out.print(randomNumber);

System.out.print(" ");

}

System.out.println("");

System.out.println("Total: " + total);

input.close();

}

}

輸出:

Enter the number of dice: 6

Hey Coder! You rolled: 2 6 3 2 2 4

Total: 19

在上面的例子中,我們要求使用者輸入骰子的總數。由於使用者輸入了 6,我們在 1 到 6 之間生成了 6 個隨機數來表示每個骰子的結果。我們為每個觀察新增結果並列印結果。

我們可以以此為基礎生成更復雜的遊戲。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe