Java Reference
In-Depth Information
a “dummy” value because we don't actually process it. Later in this chapter we will
see a variation of the
while
loop that doesn't require this kind of priming.
The following is the complete program solution:
1
import
java.util.*;
2
3
public class
Pick {
4
public static void
main(String[] args) {
5 System.out.println("This program picks numbers from");
6 System.out.println("1 to 10 until a particular");
7 System.out.println("number comes up.");
8 System.out.println();
9
10 Scanner console =
new
Scanner(System.in);
11 Random r =
new
Random();
12
13 System.out.print("Pick a number between 1 and 10——> ");
14
int
number = console.nextInt();
15
16
int
result = -1; // set to -1 to make sure we enter the loop
17
int
count = 0;
18
while
(result != number) {
19 result = r.nextInt(10) + 1; // random number from 1-10
20 System.out.println("next number = " + result);
21 count++;
22 }
23 System.out.println("Your number came up after " +
24 count + " times");
25 }
26 }
Depending on the sequence of numbers returned by the
Random
object, the program
might end up picking the given number quickly, as in the following sample execution:
This program picks numbers from
1 to 10 until a particular
number comes up.
Pick a number between 1 and 10——>
2
next number = 7
next number = 8
next number = 2
Your number came up after 3 times
Search WWH ::
Custom Search