Scanner

12
READING INPUT (SCANNER)

description

How to use scanner class in java

Transcript of Scanner

READING INPUT (SCANNER)

READING INPUT(SCANNER)ScannerScanner reads formatted input and converts it into its binary form. Although it has always been possible to read formatted input, it required more effort than most programmers would prefer. Because of the addition of Scanner, it is now easy to read all types of numeric values, strings, and other types of data, whether it comes from a disk file, the keyboard, or another source.For example, you can use Scanner to read a number from the keyboard and assign its value to a variable. The Scanner Constructors

Scanner defines the constructors

Scanning BasicsOnce you have created a Scanner, it is a simple matter to use it to read formatted input.In general, a Scanner reads tokens from the underlying source that you specified when the Scanner was created. As it relates to Scanner, a token is a portion of input that is delineated by a set of delimiters, which is whitespace by default. A token is read by matching it with a particular regular expression, which defines the format of the data. Although Scanner allows you to define the specific type of expression that its next input operation will match, it includes many predefined patterns, which match the primitive types, such as int and double, and strings. Thus, often you wont need to specify a pattern to match. In general, to use Scanner, follow this procedure:Determine if a specific type of input is available by calling one of Scanners hasNextX methods, where X is the type of data desired. If input is available, read it by calling one of Scanners nextX methods.3. Repeat the process until input is exhausted.As the preceding indicates, Scanner defines two sets of methods that enable you to read input. The first are the hasNextX methods, which are shown in Table 18-15. These methods determine if the specified type of input is available. For example, calling hasNextInt( ) returns true only if the next token to be read is an integer. If the desired data is available, then you read it by calling one of Scanners nextX methods, which are shown in Table 18-16. For example, to read the next integer, call nextInt( ). Scanner conin = new Scanner(System.in);int i;// Read a list of integers.while(conin.hasNextInt()) {i = conin.nextInt();// ...}

Example