Java Reference
In-Depth Information
1 Multiplication Quiz (continued)
10. Edit the program to enclose the section of code including the try and catch
statements in a while loop. To do this, enter the code:
while(!done)
and an opening brace before and a closing brace after that section of code.
11. Before the closing brace of the try statement, enter the line of code:
done = true;
to terminate the loop during execution. Save the file by clicking Save on the
File menu.
12. Compile and run the program again, testing with both integer and non-
integer values. Notice that users now are directed back to the beginning of
the program after the error message displays.
13. Edit the program again. In the takeQuiz() method, find the statement, while
(count <= 12). Click below the while statement's opening brace. Enclose all
the code within the while statement in a try statement. Include all the code
statements in the try statement but not the opening or closing braces of the
while statement itself. Move the line
count = count + 1;
up to position it inside the if statement braces, at approximately line 80.
14. Below the try statement, enter a catch statement for a
NumberFormatException. Print an appropriate message using the
System.out.println() method or a JOptionPane message box. Compile and
run the program again, testing with both integer and non-integer values.
Notice that the program now displays an error message if a user enters an
incorrect answer and then gives the user a chance to enter a different answer.
15. Print a copy of the revised source code for your instructor.
2 Using switch and try Statements to Validate User Input
You would like to write a program to help beginning Java programmers
understand data types. You have noticed that students have trouble differentiat-
ing among doubles, ints, Strings, and other data types. You decide to create an
application, such as the one in Figure 4-68, that uses input boxes to test their
knowledge. Beginning with a try statement, the program should allow users to
choose a data type. Then, based on a switch statement and several case state-
ments, the program should prompt the user to enter a value that would fit that
specific data type. If the user inputs valid data — that is, data that matches the
chosen data type and parses correctly — the program should display positive
feedback. If the inputted data does not match the chosen data type, the parse
statement will throw a NumberFormatException. The program then should use
a catch statement to display an appropriate error message and then allow the
user to try again.
Search WWH ::




Custom Search