Page 197 - Introduction to Programming with Java: A Problem Solving Approach
P. 197

                An Example
Let’s put the wrapper and Math.random material into practice by showing it in the context of a complete program. Figure 5.5’s Lottery program prompts the user to guess a randomly generated number between 0 and the maximum int value. The user pays $1.00 for each guess and wins $1,000,000 if the guess is cor- rect. The user enters a “q” to quit.
In the initialization of winningNumber, note how the program generates a random winning-number value:
winningNumber = (int) (Math.random() * Integer.MAX_VALUE);
The starting point is Math.random(), a random number between 0.0 and 1.0. The Adapt existing Java Virtual Machine (JVM) then multiplies by Integer.MAX_VALUE to expand the software to your range from (0.0 to 1.0) to (0.0 to 2147483647.0). The JVM then performs an (int) cast needs
to truncate the fractional component.
5.4 Wrapper Classes for Primitive Types 163
          /*********************************************************************
*
Lottery.java
Dean & Dean
This program prompts the user to choose a randomly selected number.
*********************************************************************/
*
*
*
import java.utilA.pScangneor; PDF Enhancer
public class Lottery
{
public static void main(String[] args)
  {
Scanner stdIn = new Scanner(System.in);
 String input;
int winningNumber = (int) (Math.random() * Integer.MAX_VALUE);
System.out.println("Want to win a million dollars?");
System.out.println("If so, guess the winning number (a" +
" number between 0 and " + (Integer.MAX_VALUE - 1) + ").");
System.out.print(
"Insert $1.00 and enter your number or 'q' to quit: ");
do
{
input = stdIn.nextLine();
if (input.equals("give me a hint"))
{
}
// a back door
System.out.println("try: " + winningNumber);
Initialize with scaled random number.
Figure 5.5a Lottery program illustrates use of the Integer wrapper class—part A




























































   195   196   197   198   199