Java Reference
In-Depth Information
try {
String s = buf - reader.readLine (); // read the number as a
// string
// Trim the whitespace before parsing.
tmp = Integer.parseInt (s.trim ()); // Convert string to int
System.out.println (" echo ="+ tmp);
}
catch (IOException ioe) {
System.out.println ("IO exception ="+ ioe);
}
Similar code is needed for parsing other numerical input according to the type
of values. The following text discusses an easier technique for numerical input
using the Scanner class of J2SE 5.0.
9.4.4 Text input with Scanner
The java.util.Scanner class is a very useful new tool that can parse text
for primitive types and substrings using regular expressions [4,5]. It can get the
text from various sources such as a String object, an InputStream ,a File
(Section 9.5), or a class that implements the Readable interface.
The Scanner splits its input into substrings, or tokens, separated by delim-
iters, which by default are any white space. The tokens can then be obtained
as strings or as primitive types if that is what they represent. For example, the
following code snippet shows how to read an integer from the keyboard:
Scanner scanner = new Scanner (System.in);
int i = scanner.nextInt ();
For each of the primitive types there is a corresponding nextXxx() method that
returns a value of that type. If the string cannot be interpreted as that type, then an
InputMismatchException is thrown. There is also a set of hasNextXxx()
methods, such as hasNextInt() , that return true or false according to whether
the next token matches the specified type.
import java.io.*;
import java.util.*;
/** Demonstrate the Scanner class for input of numbers.**/
public class ScanConsoleApp
{
public static void main (String arg[]) {
// Create a scanner to read from keyboard
Scanner scanner = new Scanner (System.in);
 
Search WWH ::




Custom Search