dice.java
来自「Java 入门书的源码」· Java 代码 · 共 36 行
JAVA
36 行
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.
/* Simulates the rolling of two dice.
* The use inputs the number of tosses.
* Imports the package iopack.
* Uses arrays to tabulate the results.
*/
import iopack.Io;
public class Dice {
public static int roll() {
int die1 = (int)(6*Math.random())+ 1;
int die2 = (int)(6*Math.random())+ 1;
return die1 + die2;
}
public static int[]tossResults(int number) {
int[] result = {0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int i=0; i<number; i++)
result[roll()]++;
return result;
}
public static void main(String[] args) {
int[] diceThrows; // Elements 2-12 store frequencies
int numberOfRolls; // Number of rolls of the dice
numberOfRolls = Io.readInt("Enter the number of rolls of the dice");
diceThrows = tossResults(numberOfRolls);
System.out.println("Sum\tFrequency");
for (int i=2; i<=12; i++)
System.out.println(i + "\t" +diceThrows[i]);
Io.readString("Press any key to exit"); // Added for IDE use
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?