go to previous page   go to home page   go to next page hear noise

Answer:

The size of the desired range is 11 (-5 to +5), so the parameter to nextInt() is 11. The minimum value of the desired range is -5, so add that to the expression:

val = rand.nextInt(11)-5;

The minimum of the values that nextInt(11) returns is 0; adding -5 to that gives the mimimum of the range we want.


Example Output

Here is a run of the die-tossing program:


K:\cai\>java DieToss
You toss a 2
You toss a 1
You toss a 4
You toss a 4
You toss a 6
You toss a 5
You toss a 3
You toss a 2Exception in thread "main" java.util.NoSuchElementException: No line found
        at java.util.Scanner.nextLine(Unknown Source)
        at DieToss.main(DieToss.java:15)

The user hit control-C to end the program.


QUESTION 7:

(Thought Question: ) You want to simulate the toss of two dice. Do you need two random number generators?