Java Reference
In-Depth Information
d. (x % 2 != 0) && b
e. (x / 2 == 13) || b || (z * 3 == 96)
f. (z < x) && (z > y || x >= y)
Section 5.4: User Errors
23. The following code is not robust against invalid user input. Describe how to change the code so that it will not pro-
ceed until the user has entered a valid age and grade point average (GPA). Assume that any int is a legal age and
that any double is a legal GPA.
Scanner console = new Scanner(System.in);
System.out.print("Type your age: ");
int age = console.nextInt();
System.out.print("Type your GPA: ");
double gpa = console.nextDouble();
For an added challenge, modify the code so that it rejects invalid ages (for example, numbers less than 0) and GPAs
(say, numbers less than 0.0 or greater than 4.0).
24. Consider the following code:
Scanner console = new Scanner(System.in);
System.out.print("Type something for me! ");
if (console.hasNextInt()) {
int number = console.nextInt();
System.out.println("Your IQ is " + number);
} else if (console.hasNext()) {
String token = console.next();
System.out.println("Your name is " + token);
}
What is the output when the user types the following values?
a. Jane
b. 56
c. 56.2
25. Write a piece of code that prompts the user for a number and then prints a different message depending on whether
the number was an integer or a real number. Here are two sample dialogues:
Type a number: 42.5
You typed the real number 42.5
Type a number: 3
You typed the integer 3
26. Write code that prompts for three integers, averages them, and prints the average. Make your code robust against
invalid input. (You may want to use the getInt method discussed in this chapter.)
Search WWH ::




Custom Search