Java Reference
In-Depth Information
Answers to Self-Test Exercises
1. Assuming the first item input is not a correctly formed int value, the program will
go into an infinite loop after reading the first item input. The screen will continu-
ally output a prompt for an input number. The problem is that unless the new-line
symbol '\n' is read, the program will continue to try to read on the first input line
and so continually reads in the empty string.
2. The following is the method definition embedded in a test program. This program
would give the same dialogue as the one in Display 9.1. The program is included
on the website that accompanies this topic.
extra code
on website
import java.util.Scanner;
import java.util.InputMismatchException;
public class getIntDemo
{
/**
Precondition: keyboard is an object of the class Scanner that
has been set up for keyboard input (as we have been doing right
along).
Returns: An int value entered at the keyboard.
If the user enters an incorrectly formed input, she or he
is prompted to reenter the value,
*/
public static int getInt(Scanner keyboard)
{
int number = 0; // to keep compiler happy
boolean done = false ;
while (! done)
{
try
{
System.out.println("Enter a whole number:");
number = keyboard.nextInt();
done = true ;
}
catch (InputMismatchException e)
{
keyboard.nextLine();
System.out.println(
"Not a correctly written whole number.");
System.out.println("Try again.");
}
}
return number;
}
 
Search WWH ::




Custom Search