Page 198 - Introduction to Programming with Java: A Problem Solving Approach
P. 198
164 Chapter 5 Using Pre-Built Methods
else if (!input.equals("q"))
{
}
// end else if
if (Integer.parseInt(input) == winningNumber)
{
}
else
{
}
System.out.println("YOU WIN!");
input = "q"; // if someone wins, they're forced to quit
System.out.println(
"Sorry, good guess, but not quite right.");
} while (!input.equals("q"));
System.out.println("Thanks for playing. Come again!");
} // end main
} // end Lottery class
The Integer.parseInt method converts type from String to int.
Figure 5.5b Lottery program—part B
Note how the program reads in the user’s number guess as a string:
Apago PDF Enhancer
input = stdIn.nextLine();
By reading the number guess as a string rather than a number, the program can handle the user entering a nonnumerical input, such as “q” for quit or “give me a hint” for a hint. If the user enters “q,” the program quits. If the user enters “give me a hint,” the program prints the winning number. Big hint, eh? In this case, the hint is really a backdoor. A backdoor is a secret technique for gaining access to a program. The Lottery program’s backdoor can be used for testing purposes.
If the user does not enter “q” or “give me a hint,” the program attempts to convert the user entry to a number by calling Integer.parseInt. The program then compares the converted number to the win- ning number and responds accordingly.
The Lottery program might produce the following output: Sample session:
Want to win a million dollars?
If so, guess the winning number (a number between 0 and 2147483646).
Insert $1.00 and enter your number or 'q' to quit: 66761
Sorry, good guess, but not quite right.
Insert $1.00 and enter your number or 'q' to quit: 1234567890
Sorry, good guess, but not quite right.
Insert $1.00 and enter your number or 'q' to quit: give me a hint
try 1661533855
Insert $1.00 and enter your number or 'q' to quit: 1661533855
YOU WIN!
Thanks for playing. Come again!