You know, studying from book ALWAYS brings up more questions than the book has answers.
And one of the questions I have is how the world do you ask java to randomly pick a number so you can simulate a roll of the dice. Here I will give you and example of rolling a dice to check against a preset target number of ten. Meeting or exceeding the target number will result in a success, else it will result in a failure.
import java.util.Random; this makes it possible to generate random numbers
public class targetNum {
public static void main(String[] args) {
Random dice = new Random();
Setting the random number value to dice
int playerRoll;
making a target number of 10
int targetNum = 10;
playerRoll = dice.nextInt(20)+1;
value playerRoll will be determined by the dice roll
20 means it will generate a random number between
0 and 19 so we put add the +1 to make it 1 through 20
if (playerRoll >= targetNum) {
here we say if the player roll is greater than or equal
to the target number we set, then print this line
System.out.println("Target hit");
}
Here we say if it the player rolls less than the target number then
then to print out the line Roll failed instead
else
System.out.println("Roll failed!");
}
}
Remember, I am no expert and things probably could have been done better here.
Do you know why that without the +1 that it will generate a number from 0 - 19 instead of 1 - 20?
Comment to tell people why.
No comments:
Post a Comment