Example Output

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

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?