Java Reference
In-Depth Information
You probably get a compiler warning about possible fall-through in the switch case statements, but it is
intentional. With my limited typing skills, I got the following output:
Enter an integer: 1$
"1$" is not valid input.
Try again.
Enter an integer: 14
You entered: 14
Enter a floating-point value: 2e1
You entered: 20.0
Enter a boolean value(true or false): tree
"tree" is not valid input.
Try again.
Enter a boolean value(true or false): true
You entered: true
How It Works
You use a scanner to read values of three different types from the standard input stream. The read oper-
ations take place in a loop to allow multiple attempts at correct input. Within the loop you have a rare
example of a switch statement that doesn't require a break statement after each case. In this case you
want each case to fall through to the next. The selectRead variable that selects a switch case provides
the means by which you manage subsequent attempts at correct input, because it records the case label
currently in effect.
If you enter invalid input, an InputMismatchException is thrown by the Scanner method that is at-
tempting to read a token of a particular type. In the catch block, you call the next() method for the
Scanner object to retrieve and thus skip over the input that was not recognized. You then continue with
the next while loop iteration to allow a further attempt at reading the token.
Testing for Tokens
The hasNext() method for a Scanner object returns true if another token is available from the input
source. You can use this in combination with the next() method to read a sequence of tokens of any type
from a source, delimited by whitespace. For example:
Path file = Paths.get("TryScanner.java");
try (Scanner fileScan = new Scanner(file)){
String token = null;
while(fileScan.hasNext()) {
token = fileScan.next();
// Do something with the token read...
}
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
}
Here you are just reading an arbitrary number of tokens as strings. In general, the next() method can
throw an exception of type NoSuchElementException , but this cannot happen here because you use the
hasNext() method to establish that there is another token to be read before you call the next() method.
Search WWH ::




Custom Search