This question already has an answer here:
I'm trying to do an object in Java that returns a random number with an upper bound set in objects in the main environment. I know there's loads of posts asking about dice and random numbers but I haven't found the answer anywhere or got Random
or Math
to load properly.
I'm trying to make a dice where the number of faces can be defined and a random number within that range called with CallDice
.
Since I can't get Random
or Math
to work I'm using ThreadLocalRandom
in the function. I set the lower bound to 1 (minimum on the dice) and the upper bound to diceFace + 2
. Why + 2
?? đ€ Setting both the lower and upper bounds to 1 throws an error (the upper bound must be strictly superior).
So I inserted an if
statement that runs CallDice
again if the random value that is returned is superior to the number of faces the dice has assigned (so diceResult > diceFace
).
This looks really weird because it's one of the only ways I can find which doesn't throw an error. My problem however is that it doesn't return anything in the terminal and I can't get System.out.println()
to work on any outputs.
Is my thinking going the right direction here? Does anyone have any suggestions which don't involve Random
or Math
?
import java.util.concurrent.ThreadLocalRandom;
public class Dice8 {
// create necessary objects
public Dice8(int Faces) {
diceFace = Faces;
}
private int diceFace;
private int diceResult;
// generate random number with diceDim as upper bound
public int CallDice () {
diceResult = ThreadLocalRandom.current().nextInt(1, diceFace + 2);
if (diceResult > diceFace) {
CallDice ();
} else {
}
return diceResult;
}
The only other way I found is to subtract any int from the result which is very undesirable:
public int CallDice () {
diceResult = ThreadLocalRandom.current().nextInt(1, diceFace + 2);
if (diceResult > diceFace) {
diceResult = diceResult - 1;
} else {
}
return diceResult;
}
Aucun commentaire:
Enregistrer un commentaire