我正在编写一个程序,它创建两个对象--类的/instances ( dice ) --来模拟一对骰子。程序应该模拟两个骰子的滚动,并使用OutputDice方法显示它们的值。
值字段保存骰子的值。SetValue方法在值field.The 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;
}
}
发布于 2017-03-01 00:22:31
在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());
}
}
https://stackoverflow.com/questions/42526370
复制相似问题