I am trying to write a program that creates two objects /instances of a class (Dice) to simulate a pair of dice. The program should simulate the rolling of the 2 dice and display their values using the OutputDice method.
The Value field holds the value of the dice. The SetValue method stores a value in the Value field.The GetValue method returns the value of the dice. The Roll method that generates a random number in the range of 1 through 6 for the value of the die. The OutputDice method output the value of the dice as text.
I realize that the following code is horribly incomplete but I cannot figure out how to encapsulate the random function into the output.
My two classes are as follows:
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
}
}
and
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;
}
}
-
Please describe more details of your classes and what is the question exactly.betontalpfa– betontalpfa2017年03月01日 08:17:00 +00:00Commented Mar 1, 2017 at 8:17
-
//I am not sure how to structure this section . For generating random dice values you can use Random Class in javaAbhishekkumar– Abhishekkumar2017年03月01日 08:17:47 +00:00Commented Mar 1, 2017 at 8:17
1 Answer 1
Generate the random integers in the Dice class instead of the main method.
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());
}
}