[Go to site: main page, start]

0% found this document useful (0 votes)
6 views6 pages

Java Scanner Class Overview

The Scanner class in Java is a simple text scanner that parses primitive types and strings using regular expressions, breaking input into tokens based on a delimiter pattern, which defaults to whitespace. It allows reading from various sources, including System.in and files, and supports localization for number formats. The Scanner class is not thread-safe and can throw exceptions for invalid input or null parameters.

Uploaded by

ayush.geincept
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views6 pages

Java Scanner Class Overview

The Scanner class in Java is a simple text scanner that parses primitive types and strings using regular expressions, breaking input into tokens based on a delimiter pattern, which defaults to whitespace. It allows reading from various sources, including System.in and files, and supports localization for number formats. The Scanner class is not thread-safe and can throw exceptions for invalid input or null parameters.

Uploaded by

ayush.geincept
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

compact1, compact2, compact3

[Link]

Class Scanner

[Link]

[Link]

All Implemented Interfaces:

Closeable, AutoCloseable, Iterator<String>

public final class Scanner

extends Object

implements Iterator<String>, Closeable

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types using
the various next methods.

For example, this code allows a user to read a number from [Link]:

Scanner sc = new Scanner([Link]);

int i = [Link]();

As another example, this code allows long types to be assigned from entries in a file
myNumbers:

Scanner sc = new Scanner(new File("myNumbers"));

while ([Link]()) {

long aLong = [Link]();


}

The scanner can also use delimiters other than whitespace. This example reads several items
in from a string:

String input = "1 fish 2 fish red fish blue fish";

Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]();

prints the following output:

red

blue

The same output can be generated with this code, which uses a regular expression to parse
all four tokens at once:

String input = "1 fish 2 fish red fish blue fish";

Scanner s = new Scanner(input);

[Link]("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");


MatchResult result = [Link]();

for (int i=1; i<=[Link](); i++)

[Link]([Link](i));

[Link]();

The default whitespace delimiter used by a scanner is as recognized by


[Link]. The reset() method will reset the value of the scanner's delimiter to
the default whitespace delimiter regardless of whether it was previously changed.

A scanning operation may block waiting for input.

The next() and hasNext() methods and their primitive-type companion methods (such as
nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then
attempt to return the next token. Both hasNext and next methods may block waiting for
further input. Whether a hasNext method blocks has no connection to whether or not its
associated next method will block.

The findInLine([Link]), findWithinHorizon([Link], int), and


skip([Link]) methods operate independently of the delimiter pattern. These
methods will attempt to match the specified pattern with no regard to delimiters in the
input and thus can be used in special circumstances where delimiters are not relevant. These
methods may block waiting for more input.

When a scanner throws an InputMismatchException, the scanner will not pass the token
that caused the exception, so that it may be retrieved or skipped via some other method.

Depending upon the type of delimiting pattern, empty tokens may be returned. For
example, the pattern "\\s+" will return no empty tokens since it matches multiple instances
of the delimiter. The delimiting pattern "\\s" could return empty tokens since it only passes
one space at a time.

A scanner can read text from any object which implements the Readable interface. If an
invocation of the underlying readable's [Link]([Link]) method throws
an IOException then the scanner assumes that the end of the input has been reached. The
most recent IOException thrown by the underlying readable can be retrieved via the
ioException() method.

When a Scanner is closed, it will close its input source if the source implements the
Closeable interface.

A Scanner is not safe for multithreaded use without external synchronization.

Unless otherwise mentioned, passing a null parameter into any method of a Scanner will
cause a NullPointerException to be thrown.

A scanner will default to interpreting numbers as decimal unless a different radix has been
set by using the useRadix(int) method. The reset() method will reset the value of the
scanner's radix to 10 regardless of whether it was previously changed.

Localized numbers

An instance of this class is capable of scanning numbers in the standard formats as well as in
the formats of the scanner's locale. A scanner's initial locale is the value returned by the
[Link]([Link]) method; it may be changed via the
useLocale([Link]) method. The reset() method will reset the value of the scanner's
locale to the initial locale regardless of whether it was previously changed.

The localized formats are defined in terms of the following parameters, which for a
particular locale are taken from that locale's DecimalFormat object, df, and its and
DecimalFormatSymbols object, dfs.

LocalGroupSeparator

The character used to separate thousands groups, i.e., [Link]()

LocalDecimalSeparator

The character used for the decimal point, i.e., [Link]()

LocalPositivePrefix
The string that appears before a positive number (may be empty), i.e., [Link]()

LocalPositiveSuffix

The string that appears after a positive number (may be empty), i.e., [Link]()

LocalNegativePrefix

The string that appears before a negative number (may be empty), i.e.,
[Link]()

LocalNegativeSuffix

The string that appears after a negative number (may be empty), i.e., [Link]()

LocalNaN

The string that represents not-a-number for floating-point values, i.e., [Link]()

LocalInfinity

The string that represents infinity for floating-point values, i.e., [Link]()

Number syntax

The strings that can be parsed as numbers by an instance of this class are specified in terms
of the following regular-expression grammar, where Rmax is the highest digit in the radix
being used (for example, Rmax is 9 in base 10).

NonAsciiDigit:

A non-ASCII character c for which [Link](c) returns true

Non0Digit:

[1-Rmax] | NonASCIIDigit

Digit:

[0-Rmax] | NonASCIIDigit

GroupedNumeral:

( Non0Digit Digit? Digit?

( LocalGroupSeparator Digit Digit Digit )+ )

Numeral:

( ( Digit+ ) | GroupedNumeral )

Integer:
( [-+]? ( Numeral ) )

| LocalPositivePrefix Numeral LocalPositiveSuffix

| LocalNegativePrefix Numeral LocalNegativeSuffix

DecimalNumeral:

Numeral

| Numeral LocalDecimalSeparator Digit*

| LocalDecimalSeparator Digit+

Exponent:

Common questions

Powered by AI

A Scanner can read text from any object that implements the Readable interface, which enables broader potential for input sources beyond simple input streams, such as custom objects. If an IOException is thrown during the invocation of the underlying Readable's Readable.read(java.nio.CharBuffer) method, the scanner assumes that the end of the input has been reached, and the most recent IOException can be retrieved via the ioException() method. This allows for finer control and error handling when dealing with various input sources .

The reset() method restores the Scanner's locale, delimiter, and radix to their initial default values, undoing any prior customizations. This function provides a means to reinitialize the scanner's parsing configurations to their default for subsequent operations, ensuring that any custom settings do not persist unwantedly beyond their intended scope of use. This is particularly useful for applications needing to repeatedly return to a known configuration state .

The lack of thread safety in the Scanner class means that if it is used in a multi-threaded application, external synchronization is required to prevent concurrent access issues, such as race conditions and inconsistent state. This necessitates careful management of access to a Scanner instance across different threads to ensure thread safety, potentially leading to increased complexity and potential performance bottlenecks in the application .

When a Scanner throws an InputMismatchException, it indicates that the next token does not match the expected pattern according to the current type or format. The Scanner does not pass the token that caused the exception, allowing it to be retrieved or skipped using other methods. Proper exception handling can involve checking for token availability using hasNext() methods before attempting to read using next() methods, and managing the flow of the program to either skip, handle, or log the mismatched input for further analysis or user feedback .

The useRadix(int) method in the Scanner class changes how numeric input is interpreted, allowing numbers to be processed in bases other than the default decimal (base 10). This is particularly useful when dealing with numbers in binary, octal, or hexadecimal formats. The reset() method will revert the scanner's radix to 10, affecting subsequent number parsing operations unless the radix is explicitly changed again using useRadix(int).

Closing a Scanner object will close its input source if the source implements the Closeable interface. This automatic closing behavior manages resources effectively, releasing system resources tied to the input source when the scanner is no longer in use. However, closing a Scanner that uses a non-Closeable input source will not affect the input source .

When implementing a custom scanner to parse data with complex delimiters, challenges include efficiently defining and managing regular expressions to match varied and nested delimiter patterns. The complexity increases with delimiter ambiguity and input data variability. Solutions involve using useDelimiter() with precise regular expressions to capture delimiters accurately and may involve using findInLine and similar methods to search for specific patterns independent of delimiters. Another approach is multi-pass scanning, where initial scans extract meaningful tokens that are then further processed. Additionally, maintaining robust exception handling and state management ensures resilience against unpredictable input patterns .

The Scanner class in Java uses a delimiter pattern to break its input into tokens, with the default delimiter pattern matching whitespace. The default whitespace delimiter is recognized by Character.isWhitespace and can be reset using the reset() method. Custom delimiters can be set using the useDelimiter() method. Regardless of the current delimiter, the reset() method will always revert it back to the default whitespace delimiter. The methods findInLine, findWithinHorizon, and skip can also operate independently of this delimiter for special circumstances .

A Java Scanner can match custom patterns in input using methods such as findInLine(String), findWithinHorizon(String, int), and skip(java.util.regex.Pattern), which operate independently of the delimiter pattern. These methods allow users to search for specific patterns anywhere within the input without being constrained by the current delimiter setup, making them ideal for tasks where pattern matching takes precedence over delimiter-based tokenization .

A Scanner in Java can parse numbers using both standard and locale-specific formats. The initial locale of a Scanner is the value returned by Locale.getDefault(Locale.Category.FORMAT), which can be changed using the useLocale(Locale) method. The locale settings affect the parsing of numbers via parameters like LocalGroupSeparator, LocalDecimalSeparator, LocalPositivePrefix, LocalNegativePrefix, etc., which are defined by the locale's DecimalFormat and DecimalFormatSymbols objects. These settings dictate how numbers, including their prefixes, suffixes, and decimal points, are recognized and parsed based on the current locale .

You might also like