我正在尝试编写一个程序来创建一个类(Dice)的两个对象/实例来模拟一对骰子。程序应该模拟2个骰子的滚动并使用OutputDice方法显示它们的值。
值字段包含骰子的值。 SetValue 方法在Value字段中存储一个值。 GetValue 方法返回骰子的值。 Roll 方法,为模具的值生成1到6范围内的随机数。 OutputDice 方法将骰子的值输出为文本。
我意识到以下代码非常不完整,但我无法弄清楚如何将随机函数封装到输出中。
我的两个课程如下:
import java.util.Random;
public class Dice {
private int Value;
public void setValue(int diceValue) {
Value = diceValue;
}
public int getValue() {
return Value;
}
public void roll() {
//I am not sure how to structure this section
}
}
和
import java.util.Random;
import java.util.Scanner;
public class DiceRollOutput {
public static void main(String[]args) {
String firstDie;
String secondDie;
int firstNumber;
int secondNumber;
Scanner diceRoll = new Scanner(System.in);
Random Value = new Random();
firstNumber = Value.nextInt(6)+1;
secondNumber = Value.nextInt(6)+1;
}
}
答案 0 :(得分:2)
在Dice类中生成随机整数,而不是main方法。
import java.lang.Math;
import java.util.Random;
import java.util.Scanner;
public class Dice {
private int value;
public void setValue(int diceValue) {
value = diceValue;
}
public int getValue() {
return value;
}
public void roll() {
//I am not sure how to structure this section
Random rand = new Random();
value = rand.nextInt(6) + 1;
}
}
public class DiceRollOutput {
public static void main(String[]args) {
Dice firstDie = new Dice();
Dice secondDie = new Dice();
firstDie.roll();
secondDie.roll();
System.out.println("Dice 1: "+ firstDie.getValue());
System.out.println("Dice 2: "+ secondDie.getValue());
}
}