Java Reference
In-Depth Information
When you are writing interactive programs, the simplest approach is to assume
that the user will provide good input. You can then document your preconditions and
throw exceptions when the user input isn't what was expected. In general, though, it's
better to write programs that don't make assumptions about user input. You've seen,
for example, that the Scanner object can throw an exception if the user enters the
wrong kind of data. It's preferable to write programs that can deal with user errors.
Such programs are referred to as being robust.
Robust
Ability of a program to execute even when presented with illegal data.
In this section we will explore how to write robust interactive programs. Before
you can write robust code, though, you have to understand some special functionality
of the Scanner class.
Scanner Lookahead
The Scanner class has methods that allow you to perform a test before you read a
value. In other words, it allows you to look before you leap. For each of the “next”
methods of the Scanner class, there is a corresponding “has” method that tells you
whether or not you can perform the given operation.
For example, you will often want to read an int using a Scanner object. But what
if the user types something other than an int ? Scanner has a method called
hasNextInt that tells you whether or not reading an int is currently possible. To
determine whether it is possible, the Scanner object looks at the next token and
checks whether it can be interpreted as an integer.
We tend to interpret certain sequences of characters as particular types of data, but
when we read tokens, they can be interpreted in different ways. The following pro-
gram will allow us to explore this concept:
1 import java.util.*;
2
3 public class ExamineInput1 {
4 public static void main(String[] args) {
5 System.out.println("This program examines the ways");
6 System.out.println("a token can be read.");
7 System.out.println();
8
9 Scanner console = new Scanner(System.in);
10
11 System.out.print("token? ");
12 System.out.println(" hasNextInt = " +
13 console.hasNextInt());
14 System.out.println(" hasNextDouble = " +
15 console.hasNextDouble());
 
Search WWH ::




Custom Search