Chuyển tới nội dung
Home » Scanning String In Java | Hàm Tạo Của Lớp Scanner Trong Java

Scanning String In Java | Hàm Tạo Của Lớp Scanner Trong Java

How to get String Input from a User in Java #12

Conclusion

In this article, we’ve learned how to read values containing spaces from a Scanner through examples. The article covers two scenarios, and we’ve explored different approaches to solving the problems.

As usual, all code snippets presented here are available on GitHub.

public final class Scanner extends Object implements Iterator

, Closeable

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 System.in:

Scanner sc = new Scanner(System.in); int i = sc.nextInt();

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 (sc.hasNextLong()) { long aLong = sc.nextLong(); }

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*”); System.out.println(s.nextInt()); System.out.println(s.nextInt()); System.out.println(s.next()); System.out.println(s.next()); s.close();

prints the following output:

1 2 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); s.findInLine(“(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)”); MatchResult result = s.match(); for (int i=1; i<=result.groupCount(); i++) System.out.println(result.group(i)); s.close();

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

Character

.

isWhitespace

. 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(java.lang.String)

,

findWithinHorizon(java.lang.String, int)

, and

skip(java.util.regex.Pattern)

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

Readable.read(java.nio.CharBuffer)

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 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 The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale’s 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).

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


Locale.getDefault()

method; it may be changed via the

useLocale(java.util.Locale)

method. The

reset()

method will reset the value of the
scanner’s locale to the initial locale regardless of whether it was
previously changed.

DecimalFormat

object, df, and its and

DecimalFormatSymbols

object,
dfs.

LocalGroupSeparator The character used to separate thousands groups,
i.e., dfs.


getGroupingSeparator()

LocalDecimalSeparator The character used for the decimal point,
i.e., dfs.


getDecimalSeparator()

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


getPositivePrefix()

LocalPositiveSuffix The string that appears after a positive number (may be
empty), i.e., df.


getPositiveSuffix()

LocalNegativePrefix The string that appears before a negative number (may
be empty), i.e., df.


getNegativePrefix()

LocalNegativeSuffix The string that appears after a negative number (may be
empty), i.e., df.


getNegativeSuffix()

LocalNaN The string that represents not-a-number for
floating-point values,
i.e., dfs.


getNaN()

LocalInfinity The string that represents infinity for floating-point
values, i.e., dfs.


getInfinity()

Number syntax

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

The localized formats are defined in terms of the following parameters,
which for a particular locale are taken from that locale’s

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
Non0Digit :: = [1-Rmax] | NonASCIIDigit
Digit :: = [0-Rmax] | NonASCIIDigit
GroupedNumeral ::
Numeral :: = ( ( Digit+ ) | GroupedNumeral )
Integer :: = ( [-+]? ( Numeral ) )
| LocalPositivePrefix Numeral LocalPositiveSuffix
| LocalNegativePrefix Numeral LocalNegativeSuffix
DecimalNumeral :: = Numeral
| Numeral LocalDecimalSeparator Digit*
| LocalDecimalSeparator Digit+
Exponent :: = ( [eE] [+-]? Digit+ )
Decimal :: = ( [-+]? DecimalNumeral Exponent? )
| LocalPositivePrefix DecimalNumeral LocalPositiveSuffix Exponent?
| LocalNegativePrefix DecimalNumeral LocalNegativeSuffix Exponent?
HexFloat :: = [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?
NonNumber :: = NaN | LocalNan | Infinity | LocalInfinity
SignedNonNumber :: = ( [-+]? NonNumber )
| LocalPositivePrefix NonNumber LocalPositiveSuffix
| LocalNegativePrefix NonNumber LocalNegativeSuffix
Float :: = Decimal
| HexFloat
| SignedNonNumber

Whitespace is not significant in the above regular expressions.

Constructor and Description

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Constructs a new

Modifier and Type Method and Description

Closes this scanner.

Returns the

Attempts to find the next occurrence of the specified pattern ignoring delimiters.

Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

Attempts to find the next occurrence of the specified pattern.

Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.

Returns true if this scanner has another token in its input.

Returns true if the next complete token matches the specified pattern.

Returns true if the next token matches the pattern constructed from the specified string.

Returns true if the next token in this scanner’s input can be interpreted as a

Returns true if the next token in this scanner’s input can be interpreted as a

Returns true if the next token in this scanner’s input can be interpreted as a

Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true|false”.

Returns true if the next token in this scanner’s input can be interpreted as a byte value in the default radix using the

Returns true if the next token in this scanner’s input can be interpreted as a byte value in the specified radix using the

Returns true if the next token in this scanner’s input can be interpreted as a double value using the

Returns true if the next token in this scanner’s input can be interpreted as a float value using the

Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the

Returns true if the next token in this scanner’s input can be interpreted as an int value in the specified radix using the

Returns true if there is another line in the input of this scanner.

Returns true if the next token in this scanner’s input can be interpreted as a long value in the default radix using the

Returns true if the next token in this scanner’s input can be interpreted as a long value in the specified radix using the

Returns true if the next token in this scanner’s input can be interpreted as a short value in the default radix using the

Returns true if the next token in this scanner’s input can be interpreted as a short value in the specified radix using the

Returns the

Returns this scanner’s locale.

Returns the match result of the last scanning operation performed by this scanner.

Finds and returns the next complete token from this scanner.

Returns the next token if it matches the specified pattern.

Returns the next token if it matches the pattern constructed from the specified string.

Scans the next token of the input as a

Scans the next token of the input as a

Scans the next token of the input as a

Scans the next token of the input into a boolean value and returns that value.

Scans the next token of the input as a byte.

Scans the next token of the input as a byte.

Scans the next token of the input as a double.

Scans the next token of the input as a float.

Scans the next token of the input as an int.

Scans the next token of the input as an int.

Advances this scanner past the current line and returns the input that was skipped.

Scans the next token of the input as a long.

Scans the next token of the input as a long.

Scans the next token of the input as a short.

Scans the next token of the input as a short.

Returns this scanner’s default radix.

The remove operation is not supported by this implementation of

Resets this scanner.

Skips input that matches the specified pattern, ignoring delimiters.

Skips input that matches a pattern constructed from the specified string.

Returns the string representation of this

Sets this scanner’s delimiting pattern to the specified pattern.

Sets this scanner’s delimiting pattern to a pattern constructed from the specified

Sets this scanner’s locale to the specified locale.

Sets this scanner’s default radix to the specified radix.

public Scanner(Readable source)


Scannerthat produces values scanned from the specified source.


source- A character source implementing the


Readableinterface

public Scanner(InputStream source)


Scannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform's default charset.


source- An input stream to be scanned

public Scanner(InputStream source, String charsetName)


Scannerthat produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset.


source- An input stream to be scanned


charsetName- The encoding type used to convert bytes from the stream into characters to be scanned


IllegalArgumentException- if the specified character set does not exist

public Scanner(File source) throws FileNotFoundException


Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.


source- A file to be scanned


FileNotFoundException- if source is not found

public Scanner(File source, String charsetName) throws FileNotFoundException


Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.


source- A file to be scanned


charsetName- The encoding type used to convert bytes from the file into characters to be scanned


FileNotFoundException- if source is not found


IllegalArgumentException- if the specified encoding is not found

public Scanner(Path source) throws IOException


Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.


source- the path to the file to be scanned


IOException- if an I/O error occurs opening source

public Scanner(Path source, String charsetName) throws IOException


Scannerthat produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset.


source- the path to the file to be scanned


charsetName- The encoding type used to convert bytes from the file into characters to be scanned


IOException- if an I/O error occurs opening source


IllegalArgumentException- if the specified encoding is not found

public Scanner(String source)


Scannerthat produces values scanned from the specified string.


source- A string to scan

public Scanner(ReadableByteChannel source)


Scannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the underlying platform's default charset.


source- A channel to scan

public Scanner(ReadableByteChannel source, String charsetName)


Scannerthat produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset.


source- A channel to scan


charsetName- The encoding type used to convert bytes from the channel into characters to be scanned


IllegalArgumentException- if the specified character set does not exist

public void close()

If this scanner has not yet been closed then if its underlying
readable also implements the

Closeable

interface then the readable’s close method
will be invoked. If this scanner is already closed then invoking this
method will have no effect.

Attempting to perform search operations after a scanner has
been closed will result in an

IllegalStateException

.


closein interface


Closeable


closein interface


AutoCloseable

public IOException ioException()


IOExceptionlast thrown by this


Scanner's underlying


Readable. This method returns


nullif no such exception exists.

public Pattern delimiter()


Patternthis


Scanneris currently using to match delimiters.

public Scanner useDelimiter(Pattern pattern)


pattern- A delimiting pattern

public Scanner useDelimiter(String pattern)


String.

An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation useDelimiter(Pattern.compile(pattern)).

Invoking the

reset()

method will set the scanner’s delimiter
to the default.


pattern- A string specifying a delimiting pattern

public Locale locale()

A scanner’s locale affects many elements of its default primitive matching regular expressions; see localized numbers above.

public Scanner useLocale(Locale locale)

A scanner’s locale affects many elements of its default primitive matching regular expressions; see localized numbers above.

Invoking the

reset()

method will set the scanner’s locale to
the initial locale.


locale- A string specifying the locale to use

public int radix()

A scanner’s radix affects elements of its default number matching regular expressions; see localized numbers above.

public Scanner useRadix(int radix)

A scanner’s radix affects elements of its default number matching regular expressions; see localized numbers above.

If the radix is less than

Character.MIN_RADIX

or greater than

Character.MAX_RADIX

, then an

IllegalArgumentException

is thrown.

Invoking the

reset()

method will set the scanner’s radix to

10

.


radix- The radix to use when scanning numbers


IllegalArgumentException- if radix is out of range

public MatchResult match()


IllegalStateExceptionif no match has been performed, or if the last match was not successful.

The various

next

methods of

Scanner

make a match result available if they complete without throwing an
exception. For instance, after an invocation of the

nextInt()

method that returned an int, this method returns a

MatchResult

for the search of the
Integer regular expression
defined above. Similarly the

findInLine(java.lang.String)

,

findWithinHorizon(java.lang.String, int)

, and

skip(java.util.regex.Pattern)

methods will make a
match available if they succeed.


IllegalStateException- If no match result is available

public String toString()

Returns the string representation of this

Scanner

. The
string representation of a

Scanner

contains information
that may be useful for debugging. The exact format is unspecified.

public boolean hasNext()


hasNextin interface


Iterator


IllegalStateException- if this scanner is closed


Iterator

public String next()


hasNext()returned


true.


nextin interface


Iterator


NoSuchElementException- if no more tokens are available


IllegalStateException- if this scanner is closed


Iterator

public void remove()


Iterator.


removein interface


Iterator


UnsupportedOperationException- if this method is invoked.


Iterator

public boolean hasNext(String pattern)

An invocation of this method of the form hasNext(pattern) behaves in exactly the same way as the invocation hasNext(Pattern.compile(pattern)).


pattern- a string specifying the pattern to scan


IllegalStateException- if this scanner is closed

public String next(String pattern)

An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).


pattern- a string specifying the pattern to scan


NoSuchElementException- if no such tokens are available


IllegalStateException- if this scanner is closed

public boolean hasNext(Pattern pattern)


pattern- the pattern to scan for


IllegalStateException- if this scanner is closed

public String next(Pattern pattern)


hasNext(Pattern)returned


true. If the match is successful, the scanner advances past the input that matched the pattern.


pattern- the pattern to scan for


NoSuchElementException- if no more tokens are available


IllegalStateException- if this scanner is closed

public boolean hasNextLine()


IllegalStateException- if this scanner is closed

public String nextLine()

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.


NoSuchElementException- if no line was found


IllegalStateException- if this scanner is closed

public String findInLine(String pattern)

An invocation of this method of the form findInLine(pattern) behaves in exactly the same way as the invocation findInLine(Pattern.compile(pattern)).


pattern- a string specifying the pattern to search for


IllegalStateException- if this scanner is closed

public String findInLine(Pattern pattern)


nullis returned and the scanner's position is unchanged. This method may block waiting for input that matches the pattern.

Since this method continues to search through the input looking for the specified pattern, it may buffer all of the input searching for the desired token if no line separators are present.


pattern- the pattern to scan for


IllegalStateException- if this scanner is closed

public String findWithinHorizon(String pattern, int horizon)

An invocation of this method of the form findWithinHorizon(pattern) behaves in exactly the same way as the invocation findWithinHorizon(Pattern.compile(pattern, horizon)).


pattern- a string specifying the pattern to search for


IllegalStateException- if this scanner is closed


IllegalArgumentException- if horizon is negative

public String findWithinHorizon(Pattern pattern, int horizon)

This method searches through the input up to the specified search horizon, ignoring delimiters. If the pattern is found the scanner advances past the input that matched and returns the string that matched the pattern. If no such pattern is detected then the null is returned and the scanner’s position remains unchanged. This method may block waiting for input that matches the pattern.

A scanner will never search more than

horizon

code
points beyond its current position. Note that a match may be clipped
by the horizon; that is, an arbitrary match result may have been
different if the horizon had been larger. The scanner treats the
horizon as a transparent, non-anchoring bound (see

Matcher.useTransparentBounds(boolean)

and

Matcher.useAnchoringBounds(boolean)

).

If horizon is , then the horizon is ignored and
this method continues to search through the input looking for the
specified pattern without bound. In this case it may buffer all of
the input searching for the pattern.

If horizon is negative, then an IllegalArgumentException is thrown.


pattern- the pattern to scan for


IllegalStateException- if this scanner is closed


IllegalArgumentException- if horizon is negative

public Scanner skip(Pattern pattern)

If a match to the specified pattern is not found at the current position, then no input is skipped and a NoSuchElementException is thrown.

Since this method seeks to match the specified pattern starting at the scanner’s current position, patterns that can match a lot of input (“.*”, for example) may cause the scanner to buffer a large amount of input.

Note that it is possible to skip something without risking a

NoSuchElementException

by using a pattern that can
match nothing, e.g.,

sc.skip("[ \t]*")

.


pattern- a string specifying the pattern to skip over


NoSuchElementException- if the specified pattern is not found


IllegalStateException- if this scanner is closed

public Scanner skip(String pattern)

An invocation of this method of the form skip(pattern) behaves in exactly the same way as the invocation skip(Pattern.compile(pattern)).


pattern- a string specifying the pattern to skip over


IllegalStateException- if this scanner is closed

public boolean hasNextBoolean()


IllegalStateException- if this scanner is closed

public boolean nextBoolean()


InputMismatchExceptionif the next token cannot be translated into a valid boolean value. If the match is successful, the scanner advances past the input that matched.


InputMismatchException- if the next token is not a valid boolean


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextByte()


nextByte()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public boolean hasNextByte(int radix)


nextByte()method. The scanner does not advance past any input.


radix- the radix used to interpret the token as a byte value


IllegalStateException- if this scanner is closed

public byte nextByte()

An invocation of this method of the form
nextByte() behaves in exactly the same way as the
invocation nextByte(radix), where

radix

is the default radix of this scanner.


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public byte nextByte(int radix)


InputMismatchExceptionif the next token cannot be translated into a valid byte value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined
above then the token is converted into a byte value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Byte.parseByte

with the
specified radix.


radix- the radix used to interpret the token as a byte value


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextShort()


nextShort()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public boolean hasNextShort(int radix)


nextShort()method. The scanner does not advance past any input.


radix- the radix used to interpret the token as a short value


IllegalStateException- if this scanner is closed

public short nextShort()

An invocation of this method of the form
nextShort() behaves in exactly the same way as the
invocation nextShort(radix), where

radix

is the default radix of this scanner.


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public short nextShort(int radix)


InputMismatchExceptionif the next token cannot be translated into a valid short value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined
above then the token is converted into a short value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Short.parseShort

with the
specified radix.


radix- the radix used to interpret the token as a short value


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextInt()


nextInt()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public boolean hasNextInt(int radix)


nextInt()method. The scanner does not advance past any input.


radix- the radix used to interpret the token as an int value


IllegalStateException- if this scanner is closed

public int nextInt()

An invocation of this method of the form
nextInt() behaves in exactly the same way as the
invocation nextInt(radix), where

radix

is the default radix of this scanner.


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public int nextInt(int radix)


InputMismatchExceptionif the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined
above then the token is converted into an int value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Integer.parseInt

with the
specified radix.


radix- the radix used to interpret the token as an int value


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextLong()


nextLong()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public boolean hasNextLong(int radix)


nextLong()method. The scanner does not advance past any input.


radix- the radix used to interpret the token as a long value


IllegalStateException- if this scanner is closed

public long nextLong()

An invocation of this method of the form
nextLong() behaves in exactly the same way as the
invocation nextLong(radix), where

radix

is the default radix of this scanner.


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public long nextLong(int radix)


InputMismatchExceptionif the next token cannot be translated into a valid long value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Integer regular expression defined
above then the token is converted into a long value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Long.parseLong

with the
specified radix.


radix- the radix used to interpret the token as an int value


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextFloat()


nextFloat()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public float nextFloat()


InputMismatchExceptionif the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Float regular expression defined above
then the token is converted into a float value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Float.parseFloat

. If the token matches
the localized NaN or infinity strings, then either “Nan” or “Infinity”
is passed to

Float.parseFloat

as
appropriate.


InputMismatchException- if the next token does not match the Float regular expression, or is out of range


NoSuchElementException- if input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextDouble()


nextDouble()method. The scanner does not advance past any input.


IllegalStateException- if this scanner is closed

public double nextDouble()


InputMismatchExceptionif the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.

If the next token matches the Float regular expression defined above
then the token is converted into a double value as if by
removing all locale specific prefixes, group separators, and locale
specific suffixes, then mapping non-ASCII digits into ASCII
digits via

Character.digit

, prepending a
negative sign (-) if the locale specific negative prefixes and suffixes
were present, and passing the resulting string to

Double.parseDouble

. If the token matches
the localized NaN or infinity strings, then either “Nan” or “Infinity”
is passed to

Double.parseDouble

as
appropriate.


InputMismatchException- if the next token does not match the Float regular expression, or is out of range


NoSuchElementException- if the input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextBigInteger()


BigIntegerin the default radix using the


nextBigInteger()method. The scanner does not advance past any input.


BigInteger


IllegalStateException- if this scanner is closed

public boolean hasNextBigInteger(int radix)


BigIntegerin the specified radix using the


nextBigInteger()method. The scanner does not advance past any input.


radix- the radix used to interpret the token as an integer


BigInteger


IllegalStateException- if this scanner is closed

public BigInteger nextBigInteger()


BigInteger.

An invocation of this method of the form
nextBigInteger() behaves in exactly the same way as the
invocation nextBigInteger(radix), where

radix

is the default radix of this scanner.


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if the input is exhausted


IllegalStateException- if this scanner is closed

public BigInteger nextBigInteger(int radix)


BigInteger.

If the next token matches the Integer regular expression defined
above then the token is converted into a BigInteger value as if
by removing all group separators, mapping non-ASCII digits into ASCII
digits via the

Character.digit

, and passing the
resulting string to the

BigInteger(String, int)

constructor with the specified radix.


radix- the radix used to interpret the token


InputMismatchException- if the next token does not match the Integer regular expression, or is out of range


NoSuchElementException- if the input is exhausted


IllegalStateException- if this scanner is closed

public boolean hasNextBigDecimal()


BigDecimalusing the


nextBigDecimal()method. The scanner does not advance past any input.


BigDecimal


IllegalStateException- if this scanner is closed

public BigDecimal nextBigDecimal()


BigDecimal.

If the next token matches the Decimal regular expression defined
above then the token is converted into a BigDecimal value as if
by removing all group separators, mapping non-ASCII digits into ASCII
digits via the

Character.digit

, and passing the
resulting string to the

BigDecimal(String)

constructor.


InputMismatchException- if the next token does not match the Decimal regular expression, or is out of range


NoSuchElementException- if the input is exhausted


IllegalStateException- if this scanner is closed

public Scanner reset()

Resetting a scanner discards all of its explicit state
information which may have been changed by invocations of

useDelimiter(java.util.regex.Pattern)

,

useLocale(java.util.Locale)

, or

useRadix(int)

.

An invocation of this method of the form scanner.reset() behaves in exactly the same way as the invocation

scanner.useDelimiter(“\\p{javaWhitespace}+”) .useLocale(Locale.getDefault()) .useRadix(10);

Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Scanner trong Java là gì? Có rất nhiều thảo luận về lớp đặc biệt này trong Java. Cùng CodeGym Hà Nội tìm hiểu, thảo luận về phương thức của nó và hàm tạo lớp trong Java nhé!

Nội dung

Beyond Strings with Java’s Scanner class

Java’s Scanner String input methods represent only a small part of the class’s functionality. Methods exist to directly convert input into:

  • floats
  • doubles
  • ints
  • longs
  • BigDecimal objects
  • BigInteger objects

Interestingly, there is no method for Scanner char input, although there are strategies that can be employed to make that work.

But if your program needs to take command-line input from the user in the form of a String, Java’s Scanner class provides all of the methods you will need.

Java user input and output strategies

Here’s how to get input into your Java apps and format the output.

Java User Input (Scanner)

How to get String Input from a User in Java #12
How to get String Input from a User in Java #12

Java Scanner delimiter example

By default, the scanner uses the enter key to indicate the user has finished their user input. But this can be changed by through the use of the

useDelimiter()

method.

The following Scanner example takes a String of comma-separated values (CSVs) and prints them out one at a time. The program passes the text String to the Scanner’s constructor, and then changes the delimiter to a comma.

import java.util.Scanner; public class Main { public static void main(String[] args) { String csv = “a,b,c,d,e”; Scanner scanner = new Scanner(csv); scanner.useDelimiter(“,”); while (scanner.hasNext()) { System.out.println(scanner.next()); } } }

When this Java Scanner example runs, the output is:

a b c d e

Notice that the program ignores the commas in the original text String.

Input Types

In the example above, we used the

nextLine()

method, which is used to read Strings. To read other types, look at the table below:

Method Description
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a
Reads a

In the example below, we use different methods to read data of various types:

Example


import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); System.out.println("Enter name, age and salary:"); // String input String name = myObj.nextLine(); // Numerical input int age = myObj.nextInt(); double salary = myObj.nextDouble(); // Output input by user System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Salary: " + salary); } }

Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like “InputMismatchException”).

You can read more about exceptions and how to handle errors in the Exceptions chapter.

Java Scanner String input example

The Scanner Class in Java
The Scanner Class in Java

Hàm tạo của lớp Scanner trong Java

STT

Hàm tạo

Mô tả

Scanner (Nguồn tệp) làm đối tượng Scanner tạo ra những giá trị được quét từ tệp được chỉ định
Scanner (File source, String charsetName) xây dựng đối tượng Scanner tạo ra các giá trị được quét từ tệp được chỉ định
Scanner (InputStream source) tạo ra 1 đối tượng Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (InputStream source, String charsetName) tạo 1 Scanner mới tạo ra các giá trị được quét từ luồng đầu vào được chỉ định.
Scanner (Readable source) tạo 1 Scanner mới tạo ra các giá trị được quét từ nguồn được chỉ định.
Scanner (String source) tạo 1 Scanner mới tạo ra các giá trị được quét từ chuỗi được chỉ định.
Scanner (ReadableByteChannel source) tạo 1 Scanner mới tạo ra các giá trị được quét từ kênh được chỉ định.
Scanner (ReadableByteChannel source, String charsetName) tạo 1 Máy quét mới tạo ra các giá trị được quét từ kênh được chỉ định.
Scanner (Path source) tạo 1 Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định.
10 Scanner (Path source, String charsetName) tạo 1 Scanner mới tạo ra các giá trị được quét từ tệp được chỉ định

Scanner hasNext example

To get each individual text String, we must create a loop and iterate through the input String with the Scanner’s

hasNext()

method:

System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); // Process each Java Scanner String input while (stringScanner.hasNext()) { String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); }

If the user now types in 20 30 40 50, the program iterates through the text String four times, once for each number.

Here’s the output of the updated Scanner String input processing program:

How old are you?20 30 40 5020 is a good age to be!30 is a good age to be!40 is a good age to be!50 is a good age to be!

How to use the Java Scanner next & nextLine methods for String Input
How to use the Java Scanner next & nextLine methods for String Input

Scanner user input processing

Now imagine a user types in 20 30 40 50 at the console. What happens?

Here’s the result:

How old are you?20 30 40 5020 is a good age to be!

Notice how the output includes only the first String the Java Scanner read. The rest of the text is ignored.

This is because the Scanner class tokenizes the input String based on any whitespace between words.

Scanner next vs nextLine for user input

As we have seen, the Scanner’s

next()

method consumes a line of text, tokenizes the input based on any whitespace, and then iteratively loops through each individual item. The Scanner’s

nextLine()

method works a bit differently.

In contrast to

next()

,

nextLine()

does not tokenize input. It simply returns a complete line of text.

In this example, we change from the Scanner

next()

method to the

nextLine()

method and compare the results:

System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); // Process each Java Scanner String input while (stringScanner.hasNext()) { String age = stringScanner.nextLine(); System.out.println(age + ” is a good age to be!”); }

How old are you?20 30 40 5020 30 40 50 is a good age to be!

Notice how the input is not split up, or tokenized, into separate, individual Strings?

The difference between the Java Scanner’s

next()

and

nextLine()

methods is that

next()

chunks a line of input into individual text Strings, while

nextLine()

returns an entire line of user input exactly the way it was sent to the Scanner.

Java Scanner Tutorial #14
Java Scanner Tutorial #14

Scanner next vs nextLine for user input

As we have seen, the Scanner’s

next()

method consumes a line of text, tokenizes the input based on any whitespace, and then iteratively loops through each individual item. The Scanner’s

nextLine()

method works a bit differently.

In contrast to

next()

,

nextLine()

does not tokenize input. It simply returns a complete line of text.

In this example, we change from the Scanner

next()

method to the

nextLine()

method and compare the results:

System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); // Process each Java Scanner String input while (stringScanner.hasNext()) { String age = stringScanner.nextLine(); System.out.println(age + ” is a good age to be!”); }

How old are you?20 30 40 5020 30 40 50 is a good age to be!

Notice how the input is not split up, or tokenized, into separate, individual Strings?

The difference between the Java Scanner’s

next()

and

nextLine()

methods is that

next()

chunks a line of input into individual text Strings, while

nextLine()

returns an entire line of user input exactly the way it was sent to the Scanner.

Scanner hasNext example

To get each individual text String, we must create a loop and iterate through the input String with the Scanner’s

hasNext()

method:

System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); // Process each Java Scanner String input while (stringScanner.hasNext()) { String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); }

If the user now types in 20 30 40 50, the program iterates through the text String four times, once for each number.

Here’s the output of the updated Scanner String input processing program:

How old are you?20 30 40 5020 is a good age to be!30 is a good age to be!40 is a good age to be!50 is a good age to be!

How To Get Array Input From A User In Java Using Scanner
How To Get Array Input From A User In Java Using Scanner

Values Separated by a Special Separator

Sometimes, our input has a predefined format. For example, a comma and a space separate an input line of three great artists’ names: “Michael Jackson, Whitney Houston, John Lennon“.

Next, let’s see how to read expected values in this scenario.

4.Using the String.split() Method

The first idea for solving this problem is still reading the entire line using nextLine(). Then, we can pass the separator pattern to the convenient String.split() method to get the values in an array:


String input = "Michael Jackson, Whitney Houston, John Lennon\n";
Scanner sc = new Scanner(input);
String[] names = sc.nextLine().split(", ");
assertArrayEquals(new String[] { "Michael Jackson", "Whitney Houston", "John Lennon" }, names);

The test above shows we’ve stored the three names in a string array correctly.

4.Customizing the Delimiter

The split() with the separator pattern approach can handle values with a custom separator. However, as arrays have fixed sizes in Java, merging arrays can be slow if the scanner input has multiple lines.

Usually, we’d use lists over arrays in Java. So next, let’s adjust the Scanner’s delimiter and store the names in a list using Scanner’s next() method.

We’ve learned to use the useDelimiter() method to set a custom delimiter pattern. Since the separator of this input example is a comma and space, some of us may come up with the idea: useDelimiter(“, “).

So next, let’s add one more name to the input and see if this idea works as expected:


String input = new StringBuilder().append("Michael Jackson, Whitney Houston, John Lennon\n")
.append("Elvis Presley\n")
.toString();
Scanner sc = new Scanner(input);
sc.useDelimiter(", ");
List

names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names);

The test fails if we give it a run. What a surprise! So, let’s figure out what we have in the list through a couple of assertions:


assertEquals(3, names.size());
assertEquals("John Lennon\nElvis Presley\n", names.get(2));

We can see our result list has three elements instead of four. Also the third element is “John Lennon\nElvis Presley\n”. This is because we’ve set “, ” as the delimiter. Then, newlines become parts of a token. So the next() method will treat newlines as other regular characters in the token.

Now we understand the cause of the problem. Then it’s easy to fix – we must add ‘\n‘ to the delimiter pattern:


Scanner sc = new Scanner(input);
sc.useDelimiter(", |\\n");
List

names = new ArrayList<>();
while (sc.hasNext()) {
names.add(sc.next());
}
assertEquals(Lists.newArrayList("Michael Jackson", "Whitney Houston", "John Lennon", "Elvis Presley"), names);

This time, the test passes.

Java’s Scanner String input method

To take String input from the user with Java’s Scanner class, just follow these steps

  1. Import

    java.util.*;

    to make Java’s Scanner class available
  2. Use the new keyword to create an instance of the Scanner class
  3. Pass the static

    System.in

    object to the Scanner’s constructor
  4. Use Scanner’s

    next()

    method to take input one String at a time
  5. Optionally use the Scanner’s

    hasNext()

    method to loop over the process
#83 User Input using BufferedReader and Scanner in Java
#83 User Input using BufferedReader and Scanner in Java

One Value per Line

Let’s first take a closer look at the “one value per line” scenario. We’ll still use the previous “Michael Jackson” example as the input in this section.

3.Using the nextLine() Method

Since we want to read an entire line from the scanner as a value, the Scanner’s nextLine() method is a good choice. The nextLine() method reads from the current position until the next line break:


Scanner sc = new Scanner(input);
String name = sc.nextLine();
String description = sc.nextLine();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);

As the code above shows, nextLine() solves the problem straightforwardly.

3.Using ‘\n‘ as the Delimiter

We’ve mentioned earlier that Scanner treats space and line breaks as delimiters by default. If we tell Scanner only to take the newline character as a delimiter, we can still use the next() method to read a line as a token. Let’s create a test to verify it:


Scanner sc = new Scanner(input);
sc.useDelimiter("\\n");
String name = sc.next();
String description = sc.next();
assertEquals("Michael Jackson", name);
assertEquals("He was the 'King of Pop'.", description);

As we can see, the useDelimiter() method is the key to solving the problem.

Java Scanner Methods to Take Input

The

Scanner

class provides various methods that allow us to read inputs of different types.

Method Description
reads an
reads a
reads a
reads a line of text from the user
reads a word from the user
reads a
reads a
reads a
reads a
Scanner Class 2 Part 1:  Splitting Strings (Java)
Scanner Class 2 Part 1: Splitting Strings (Java)

Example 3

Output:

Boolean Result: false
—Tokenizes String—
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /

The

Scanner

class of the

java.util

package is used to read input data from different sources like input streams, files, etc. Let’s take an example.

Scanner trong java là gì?

Có nhiều bạn hỏi “Scanner java là gì?” hay “Scanner trong java là gì?”

Scanner trong Java là gì?

Scanner trong Java là lớp được dùng để đọc dữ liệu đầu vào từ các nguồn khác nhau như luồng đầu vào, người dùng, tệp. Đây là lớp có trong gói java.util, và gói này cần được nhập vào bên trong chương trình java để lớp scanner được chạy. Với nhiều phương thức được xác định trước trong lớp java.util.Scanner để thực hành các hoạt động khác nhau như: đọc hay phân tách cú pháp những kiểu nguyên thủy khác nhau. Bằng cách dùng biểu thức chính quy, lớp Scanner cũng có thể phân tích cú pháp dạng chuỗi và kiểu nguyên thủy

Lớp Scanner trong Java mở rộng lớp Object và triển khai được các giao diện Cloneable và Iterator.

Scanner Class - Character Input
Scanner Class – Character Input

Introduction to the Problem

As usual, let’s understand the problem with a simple example.

Let’s say our scanner receives two lines of text. The first one is a person’s name, and the second line describes the person briefly:


String input = new StringBuilder().append("Michael Jackson\n")
.append("He was the 'King of Pop'.\n")
.toString();
Scanner sc = new Scanner(input);

For simplicity, we’ll feed Scanner objects with strings and use unit test assertions to verify if the results are expected.

Usually, we’ll use the Scanner.next() method to read the next token from the scanner.

Next, let’s try to read two tokens from our scanner object:


String name = sc.next();
String description = sc.next();
assertEquals("Michael", name);
assertEquals("Jackson", description);

If we run the test, it passes. Obviously, Scanner doesn’t intelligently understand our requirements. Instead, it uses whitespace, including spaces and line breaks, as the default delimiter to read tokens. Therefore, we’ve got “Michael” instead of “Michael Jackson“ as the person’s name.

Actually, this example presents only one scenario of handling input values containing spaces. There can be two scenarios:

  • One value per line, as our “Michael Jackson” example shows
  • Values separated by a special separator

Next, we’ll figure out how to read the values containing spaces from a Scanner object. Of course, we’ll cover both scenarios.

Java Scanner char input example

Interestingly, the Java Scanner char input is not supported through a defined method in the Scanner class.

However, it is possible to have a Scanner input one char at a time through the use of the delimiter setting and the Scanner’s

hasNext()

method.

The following example takes char input with the Scanner:

import java.util.Scanner; public class NextCharScanner{ // Java Scanner char input example public static void main(String[] args) { System.out.println(“Provide the Java Scanner char input: “); Scanner charScanner = new Scanner(System.in); charScanner.useDelimiter(“”); while (charScanner.hasNext()) { char name = charScanner.next().charAt(0); if (name == ‘\n’) { return; } } } }

Useful JavaScript STRING METHODS 🧵
Useful JavaScript STRING METHODS 🧵

Java Scanner String example

One thing I don’t like about Java’s Scanner class, especially when it’s taught to novice Java programmers, is that it introduces several advanced concepts. Specifically, these are:

  • Import statements — the java.util package must be imported.
  • The new keyword — an instance of the Scanner must be instantiated.

If those two advanced topics don’t intimidate the developer, then user input with Java’s Scanner class is a lead-pipe cinch.

import java.util.Scanner; public class ScannerUserInput { public static void main(String[] args) { // Java Scanner String input example System.out.println(“What is your name?”); Scanner scanner = new Scanner(System.in); String name = scanner.nextLine(); System.out.println(name + ” is a nice name!”); } }

In the example above of how to use Java’s Scanner for user input, the import statement is at the start of the code, along with the creation of an instance of the Scanner with the new keyword. The import can optionally be removed if Java’s Scanner class explicitly references the package.

Java user input made easy

Learn the easiest ways to handle user input in Java, and format any console output with printf.

Create a Scanner Object in Java

Once we import the package, here is how we can create

Scanner

objects.


// read input from the input stream Scanner sc1 = new Scanner(InputStream input); // read input from files Scanner sc2 = new Scanner(File file); // read input from a string Scanner sc3 = new Scanner(String str);

Here, we have created objects of the

Scanner

class that will read input from InputStream, File, and String respectively.

Day 3 : Basic IO & Scanner Class in Telugu | Java Course in Telugu | Vamsi Bhavani
Day 3 : Basic IO & Scanner Class in Telugu | Java Course in Telugu | Vamsi Bhavani

Dùng lớp Scanner trong Java

Nhập lớp Scanner xong, chúng ta phải lấy kết quả thể hiện của lớp này để đọc đầu vào từ người dùng.

Ví dụ:

Ta sẽ thực hiện một thí dụ như sau.


import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Nhap mot tu bat ky: "); String chuoi_ky_tu = input.nextLine(); System.out.println(chuoi_ky_tu); input.close(); } }

Kết quả:


Nhap mot tu bat ky: xin chao xin chao

Trong ví dụ trên, câu lệnh:


Scanner input = new Scanner(System.in);

Ở đây, ta đã tạo một đối tượng của lớp Scanner có tên là

input

. Tham số

System.in

được dùng để lấy đầu vào. Tiếp theo, ta đã dùng phương thức

nextLine()

của lớp Scanner để đọc một chuỗi ký tự từ người dùng.

Từ ví dụ trên, ta cần thêm gói

java.util.Scanner

trước khi có thể dùng lớp Scanner.


import java.util.Scanner;

>> Đọc thêm: Khóa học lập trình Java

Nhập lớp Scanner trong Java

Để dùng những phương thức và chức năng của lớp Scanner, chúng ta cần nhập lớp vào chương trình Java của mình bằng cách nhập gói java.util bằng phương pháp dùng từ khóa import ở đầu mã.

Hai cách mà ta có thể làm như sau:


  1. import java.util.Scanner;

//nhập lớp Scanner trong Java


  1. import java.util.*;

//nhập hết những lớp của gói trong

java.util

Spring Boot & Spring Data JPA – Complete Course
Spring Boot & Spring Data JPA – Complete Course

Example 5: Java Scanner nextLine()


import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire line String value = input.nextLine(); System.out.println("Using nextLine(): " + value); input.close(); } }

Output

Enter your name: Jonny Walker Using nextLine(): Jonny Walker

In the first example, we have used the

nextLine()

method to read a string from the user.

Unlike

next()

, the

nextLine()

method reads the entire line of input including spaces. The method is terminated when it encounters a next line character,

\n

.

To learn more, visit Java Scanner skipping the nextLine().

Working of Java Scanner

The

Scanner

class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example,

Suppose there is an input string:


He is 22

In this case, the scanner object will read the entire line and divides the string into tokens: “He”, “is” and “22”. The object then iterates over each token and reads each token using its different methods.

Note: By default, whitespace is used to divide tokens.

Also Read: Basic Input/Output

Java Scanner User Input Example

Tips For Reading Code
Tips For Reading Code

Java Scanner Class Methods

The following are the list of Scanner methods:

SN Modifier & Type Method Description
1) void close() It is used to close this scanner.
2) pattern delimiter() It is used to get the Pattern which the Scanner class is currently using to match delimiters.
3) Stream findAll() It is used to find a stream of match results that match the provided pattern string.
4) String findInLine() It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
5) string findWithinHorizon() It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
6) boolean hasNext() It returns true if this scanner has another token in its input.
7) boolean hasNextBigDecimal() It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
8) boolean hasNextBigInteger() It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
9) boolean hasNextBoolean() It is used to check if the next token in this scanner’s input can be interpreted as a Boolean using the nextBoolean() method or not.
10) boolean hasNextByte() It is used to check if the next token in this scanner’s input can be interpreted as a Byte using the nextBigDecimal() method or not.
11) boolean hasNextDouble() It is used to check if the next token in this scanner’s input can be interpreted as a BigDecimal using the nextByte() method or not.
12) boolean hasNextFloat() It is used to check if the next token in this scanner’s input can be interpreted as a Float using the nextFloat() method or not.
13) boolean hasNextInt() It is used to check if the next token in this scanner’s input can be interpreted as an int using the nextInt() method or not.
14) boolean hasNextLine() It is used to check if there is another line in the input of this scanner or not.
15) boolean hasNextLong() It is used to check if the next token in this scanner’s input can be interpreted as a Long using the nextLong() method or not.
16) boolean hasNextShort() It is used to check if the next token in this scanner’s input can be interpreted as a Short using the nextShort() method or not.
17) IOException ioException() It is used to get the IOException last thrown by this Scanner’s readable.
18) Locale locale() It is used to get a Locale of the Scanner class.
19) MatchResult match() It is used to get the match result of the last scanning operation performed by this scanner.
20) String next() It is used to get the next complete token from the scanner which is in use.
21) BigDecimal nextBigDecimal() It scans the next token of the input as a BigDecimal.
22) BigInteger nextBigInteger() It scans the next token of the input as a BigInteger.
23) boolean nextBoolean() It scans the next token of the input into a boolean value and returns that value.
24) byte nextByte() It scans the next token of the input as a byte.
25) double nextDouble() It scans the next token of the input as a double.
26) float nextFloat() It scans the next token of the input as a float.
27) int nextInt() It scans the next token of the input as an Int.
28) String nextLine() It is used to get the input string that was skipped of the Scanner object.
29) long nextLong() It scans the next token of the input as a long.
30) short nextShort() It scans the next token of the input as a short.
31) int radix() It is used to get the default radix of the Scanner use.
32) void remove() It is used when remove operation is not supported by this implementation of Iterator.
33) Scanner reset() It is used to reset the Scanner which is in use.
34) Scanner skip() It skips input that matches the specified pattern, ignoring delimiters
35) Stream tokens() It is used to get a stream of delimiter-separated tokens from the Scanner object which is in use.
36) String toString() It is used to get the string representation of Scanner using.
37) Scanner useDelimiter() It is used to set the delimiting pattern of the Scanner which is in use to the specified pattern.
38) Scanner useLocale() It is used to sets this scanner’s locale object to the specified locale.
39) Scanner useRadix() It is used to set the default radix of the Scanner which is in use to the specified radix.

Kết luận

Lớp Scanner trong Java bạn có thể hiểu và tưởng tượng là một “cái máy in”, có thể nhập và xuất ra dữ liệu. Bài viết trên đã giới thiệu cho bạn về lớp Scanner trong Java, cho bạn rõ hơn định nghĩa Scanner trong Java là gì? Và các phương thức và hàm tạo của lớp Scanner. Mong rằng bạn có thể hiểu rõ hơn về Scanner trong Java qua bài viết này. Tìm hiểu thêm về Java và các ngôn ngữ lập trình khác qua các khóa học lập trình chuyển nghiệp tại CodeGym Hà Nội bạn nhé!

Tin bài liên quan:

https://hanoi.codegym.vn/blog/co-nen-hoc-java-web-khong/

https://hanoi.codegym.vn/blog/lo-trinh-hoc-lap-trinh-java-hieu-qua/

How to import the Java Scanner
How to import the Java Scanner

Java


import


java.util.Scanner;


public


class


ScannerDemo1 {


public


static


void


main(String[] args)


Scanner sc =


new


Scanner(System.in);


String name = sc.nextLine();


char


gender = sc.next().charAt(


);


int


age = sc.nextInt();


long


mobileNo = sc.nextLong();


double


cgpa = sc.nextDouble();


System.out.println(


"Name: "


+ name);


System.out.println(


"Gender: "


+ gender);


System.out.println(


"Age: "


+ age);


System.out.println(


"Mobile Number: "


+ mobileNo);


System.out.println(


"CGPA: "


+ cgpa);

Input

GeekF4098765432109.9

Output

Name: GeekGender: FAge: 40Mobile Number: 9876543210CGPA: 9.9

Sometimes, we have to check if the next value we read is of a certain type or if the input has ended (EOF marker encountered).

Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).

Example 2:

Let us look at the code snippet to read some numbers from the console and print their mean.

Example 2: Java Scanner nextInt()


import java.util.Scanner; class Main { public static void main(String[] args) { // creates a Scanner object Scanner input = new Scanner(System.in); System.out.println("Enter an integer: "); // reads an int value int data1 = input.nextInt(); System.out.println("Using nextInt(): " + data1); input.close(); } }

Output

Enter an integer: 22 Using nextInt(): 22

In the above example, we have used the

nextInt()

method to read an integer value.

I Read the Entire Neovim User Manual
I Read the Entire Neovim User Manual

Scanner user input processing

Now imagine a user types in 20 30 40 50 at the console. What happens?

Here’s the result:

How old are you?20 30 40 5020 is a good age to be!

Notice how the output includes only the first String the Java Scanner read. The rest of the text is ignored.

This is because the Scanner class tokenizes the input String based on any whitespace between words.

Example 4: Java Scanner next()


import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // reads the entire word String value = input.next(); System.out.println("Using next(): " + value); input.close(); } }

Output

Enter your name: Jonny Walker Using next(): Jonny

In the above example, we have used the

next()

method to read a string from the user.

Here, we have provided the full name. However, the

next()

method only reads the first name.

This is because the

next()

method reads input up to the whitespace character. Once the whitespace is encountered, it returns the string (excluding the whitespace).

Learn Java in 14 Minutes (seriously)
Learn Java in 14 Minutes (seriously)

Cách thức hoạt động của Lớp Scanner

Lớp Scanner đọc toàn bộ dòng ký tự và chia thành các token. Ta có thể tạm hiểu token là các thành phần nhỏ có ý nghĩa đối với trình biên dịch trong Java.

Ví dụ: Giả sử có một chuỗi đầu vào như sau.


Xin chao moi nguoi

Trong trường hợp này, đối tượng lớp Scanner sẽ đọc toàn bộ dòng ký tự và chia thành các token: “Xin”, “chao”, “moi” và “nguoi”. Đối tượng sau đó thực hiện vòng lặp duyệt qua từng token và đọc từng token bằng các phương thức khác nhau.

Chú ý: Theo mặc định, khoảng trắng sẽ được dùng để phân chia các token.

Trên đây là khái niệm và ví dụ cơ bản về lớp Scanner trong Java. Hy vọng các bạn có thể áp dụng được vào trong chương trình của mình. Mọi người hãy tiếp tục theo dõi các bài tiếp theo và cập nhật các bài mới nhất trên CodeGym Hà Nội nhé!

Java’s Scanner String input method

To take String input from the user with Java’s Scanner class, just follow these steps

  1. Import

    java.util.*;

    to make Java’s Scanner class available
  2. Use the new keyword to create an instance of the Scanner class
  3. Pass the static

    System.in

    object to the Scanner’s constructor
  4. Use Scanner’s

    next()

    method to take input one String at a time
  5. Optionally use the Scanner’s

    hasNext()

    method to loop over the process
Scanner in Java in Telugu || Getting input from the user in java telugu  || Kotha Abhishek
Scanner in Java in Telugu || Getting input from the user in java telugu || Kotha Abhishek

Beyond Strings with Java’s Scanner class

Java’s Scanner String input methods represent only a small part of the class’s functionality. Methods exist to directly convert input into:

  • floats
  • doubles
  • ints
  • longs
  • BigDecimal objects
  • BigInteger objects

Interestingly, there is no method for Scanner char input, although there are strategies that can be employed to make that work.

But if your program needs to take command-line input from the user in the form of a String, Java’s Scanner class provides all of the methods you will need.

Java user input and output strategies

Here’s how to get input into your Java apps and format the output.

SCAN (Scan String)

Free-Form Syntax (not allowed – use the %SCAN built-in function)
Code Factor 1 Factor 2 Result Field Indicators
SCAN (E) Compare string:length Base string:start Left-most position ER FD

The SCAN operation scans a string (base string) contained in factor 2 for a substring (compare string) contained in factor 1. The scan begins at a specified location contained in factor 2 and continues for the length of the compare string which is specified in factor 1. The compare string and base string must both be of the same type, either both character, both graphic, or both UCS-2.

Factor 1 must contain either the compare string or the compare string, followed by a colon, followed by the length. The compare string portion of factor 1 can contain one of: a field name, array element, named constant, data structure name, literal, or table name. The length portion must be numeric with no decimal positions and can contain one of: a named constant, array element, field name, literal, or table name. If no length is specified, it is that of the compare string.

Factor 2 must contain either the base string or the base string, followed by a colon, followed by the start location of the SCAN. The base string portion of factor 2 can contain one of: a field name, array element, named constant, data structure name, literal, or table name. The start location portion of factor 2 must be numeric with no decimal positions and can be a named constant, array element, field name, literal, or table name. If graphic or UCS-2 strings are used, the start position and length are measured in double bytes. If no start location is specified, a value of 1 is used.

  1. The strings are indexed from position 1.
  2. If the start position is greater than 1, the result field contains the position of the compare string relative to the beginning of the source string, not relative to the start position.
  3. Figurative constants cannot be used in the factor 1, factor 2, or result fields.
  4. No overlapping within data structures is allowed for factor 1 and the result field or factor 2 and the result field.

To handle SCAN exceptions (program status code 100), either the operation code extender ‘E’ or an error indicator ER can be specified, but not both. An error occurs if the start position is greater than the length of factor 2 or if the value of factor 1 is too large. For more information on error handling, see Program Exception/Errors.

You can specify an indicator in positions 75-76 that is set on if the string being scanned for is found. This information can also be obtained from the %FOUND built-in function, which returns ‘1’ if a match is found.

The SCAN begins at the leftmost character of factor 2 (as specified by the start location) and continues character by character, from left to right, comparing the characters in factor 2 to those in factor 1. If the result field is not an array, the SCAN operation will locate only the first occurrence of the compare string. To continue scanning beyond the first occurrence, use the result field from the previous SCAN operation to calculate the starting position of the next SCAN. If the result field is a numeric array, as many occurrences as there are elements in the array are noted. If no occurrences are found, the result field is set to zero; if the result field is an array, all its elements are set to zero.

Leading, trailing, or embedded blanks specified in the compare string are included in the SCAN operation.

The SCAN operation is case-sensitive. A compare string specified in lowercase will not be found in a base string specified in uppercase.

For more information, see String Operations.


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.... * * The SCAN operation finds the substring 'ABC' starting in * position 3 in factor 2; 3 is placed in the result field. * Indicator 90 is set on because the string is found. Because * no starting position is specified, the default of 1 is used. C 'ABC' SCAN 'XCABCD' RESULT 90 * * This SCAN operation scans the string in factor 2 for an * occurrence of the string in factor 1 starting at position 3. * The 'Y' in position 1 of the base string is ignored because * the scan operation starts from position 3. * The operation places the values 5 and 6 in the first and * second elements of the array. Indicator 90 is set on. C C MOVE 'YARRYY' FIELD1 6 C MOVE 'Y' FIELD2 1 C FIELD2 SCAN FIELD1:3 ARRAY 90 * * This SCAN operation scans the string in factor 2, starting * at position 2, for an occurrence of the string in factor 1 * for a length of 4. Because 'TOOL' is not found in FIELD1, * INT is set to zero and indicator 90 is set off. C C MOVE 'TESTING' FIELD1 7 C Z-ADD 2 X 1 0 C MOVEL 'TOOL' FIELD2 5 C FIELD2:4 SCAN FIELD1:X INT90 20 C * * The SCAN operation is searching for a name. When the name * is found, %FOUND returns '1' so HandleLine is called. C SrchName SCAN Line C IF %FOUND C EXSR HandleLine C ENDIF


*...1....+....2....+....3....+....4....+....5....+....6....+....7...+.... DName+++++++++++ETDsFrom+++To/L+++IDc.Functions+++++++++++++++++++++++++ * * A Graphic SCAN example * * Value of Graffld is graphic 'AACCBBGG'. * Value of Number after the scan is 3 as the 3rd graphic * character matches the value in factor 1 D Graffld S 4G inz(G'oAACCBBGGi') CL0N01Factor1+++++++Opcode(E)+Factor2+++++++Result++++++++Len++D+HiLoEq.. * The SCAN operation scans the graphic string in factor 2 for * an occurrence of the graphic literal in factor 1. As this is a * graphic operation, the SCAN will operate on 2 bytes at a time C C G'oBBi' SCAN Graffld:2 Number 5 0 90 C

Java Scanner nextLine() Method

The nextLine() method of Java Scanner class is used to get the input string that was skipped of the Scanner object.

Syntax

Following is the declaration of nextLine() method:

Parameter

This method does not accept any parameter.

Returns

The nextLine() method returns the the line that was skipped.

Exceptions

NoSuchElementException- It will thrown this Exception if no line was found.

IllegalStateException- It will thrown this Exception if the innvocation is done after Scanner is closed.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Enter Item ID: A151 Enter Item price: 3473.75 Price of Item A151 is $3473.75

Example 2

Output:

hasNextLine public boolean hasNextLine() IllegalStateException

Example 3

Output:

Facebook.com true 1 + 1 = 2.0 true JavaTpoint.com false

Next TopicJava Scanner Class

How to Find a word or substring in String

In this post, we are finding a word or substring in the String. The String is a sequence of characters and a class in Java.

To find a word in the string, we are using indexOf() and contains() methods of String class.

The

indexOf()

method is used to find an index of the specified substring in the present string. It returns a positive integer as an index if substring found else returns -1.

The

contains()

method is used to check whether a string contains the specified string or not. It returns a boolean value either true or false. If the specified string is found then it returns true, false otherwise.

String user input example

The following example uses the Java Scanner class to take String input from the user:

import java.util.Scanner; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }

Console-based interaction with this example looks like this:

How old are you? 50 50 is a good age to be!

Avoiding Issues with nextInt() followed by nextLine()
Avoiding Issues with nextInt() followed by nextLine()

How to use the Java Scanner for user input

The Java Scanner class is a simple, versatile, easy-to-use class that makes user input in Java relatively straightforward.

To perform user input with the Scanner class, follow these steps:

  1. Create an instance of the Scanner with the new keyword.
  2. Specify the System.in as the argument for the Scanner constructor.
  3. Optionally set a delimiter other than the enter key.
  4. Use the Scanner’s

    next ()

    or

    nextLine()

    methods to convert user input into the appropriate type.
  5. Use the Java user input in your program.

Java User Input

The

Scanner

class is used to get
user input, and it is found in the

java.util

package.

To use the

Scanner

class, create an object of the class and use any of the available methods found in the

Scanner

class documentation.
In our example, we will use the

nextLine()

method, which is used to read Strings:

Example


import java.util.Scanner; // Import the Scanner class class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }

If you don’t know what a package is, read our Java Packages Tutorial.

Checked vs. Unchecked Exceptions in Java Tutorial - What's The Difference?
Checked vs. Unchecked Exceptions in Java Tutorial – What’s The Difference?

Example 4: Read BigInteger and BigDecimal


import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter a big integer: "); // reads the big integer BigInteger value1 = input.nextBigInteger(); System.out.println("Using nextBigInteger(): " + value1); System.out.print("Enter a big decimal: "); // reads the big decimal BigDecimal value2 = input.nextBigDecimal(); System.out.println("Using nextBigDecimal(): " + value2); input.close(); } }

Output

Enter a big integer: 987654321 Using nextBigInteger(): 987654321 Enter a big decimal: 9.55555 Using nextBigDecimal(): 9.55555

In the above example, we have used the

java.math.BigInteger

and

java.math.BigDecimal

package to read

BigInteger

and

BigDecimal

respectively.

Java Scanner vs Console for user input

The easiest way to garner input from the user in a Java program is through the Console class.

But Java’s Console class has two big disadvantages:

  • It does not work in IDEs like Eclipse.
  • It can only return user input as a String.

A more versatile approach to Java user input is the Scanner class.

And those are the ins and outs on how to use the Java Scanner for user input.

How to accept user input in Java ⌨️【8 minutes】
How to accept user input in Java ⌨️【8 minutes】

Các phương thức của lớp Scanner để lấy đầu vào

Lớp Scanner cung cấp các phương thức khác nhau cho phép chúng ta đọc các đầu vào thuộc các kiểu khác nhau.

Phương thức Mô tả
nextInt() Đọc một giá trị kiểu int.
nextFloat() Đọc một giá trị kiểu float.
nextBoolean() Đọc một giá trị kiểu Boolean.
nextLine() Đọc một dòng văn bản.
next() Đọc một từ.
nextByte() Đọc một giá trị ở dạng byte.
nextDouble() Đọc một giá trị kiểu double.
nextShort() Đọc một giá trị kiểu short.
nextLong() Đọc một giá trị kiểu long.

Có thể hiểu phương thức của Scanner bằng một ví dụ thực tiễn sau:


import java.util.Scanner; class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Nhap mot so nguyen: "); int a = input.nextInt(); System.out.println(a); input.close(); } }

Kết quả:


Nhap mot so nguyen: 4 4 hasNextXYZ ()

Trong ví dụ trên, chúng ta đã dùng phương thức nextInt() để đọc 1 giá trị là số nguyên.

Nextline trong java là gì?Hasnextline trong java là gì

Đôi lúc ta cần kiểm tra xem giá trị tiếp theo ta đọc có thuộc một loại nào không, hoặc đầu vào có EOF hay không. Tiếp theo, mình nên kiểm tra xem đầu vào của máy quét có thuộc loại mình muốn hay không? Với sự trợ giúp của các hàm hasNextXYZ () trong đó XYZ là kiểu dữ liệu mà minh muốn dùng. Phương thức trả về true (đúng) khi máy quét có mã thông báo thuộc loại đó ngược lại trả về false (sai). Với một số phương thức boolean cho mỗi mẫu dữ liệu. Để ta rà soát xem mã thông báo tiếp theo của một mẫu dữ liệu cụ thể có sẵn trong đầu vào nhất định hay không?

Ta có bảng sau:

Phương thức Mô tả
boolean hasNextBoolean () kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu Boolean bằng phương thức nextBoolean () hay không
boolean hasNextByte () kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu là Byte bằng cách dùng phương thức nextByte () hay không
boolean hasNextDouble () kiểm tra mã thông báo tiếp theo trong máy quét này có phải đầu vào BigDecimal bằng cách dùng phương thức nextBigDecimal () hay không
boolean hasNextFloat () Phương pháp này kiểm tra xem mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu một Float bằng cách dùng phương thức nextFloat () hay không
boolean hasNextInt () kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu một int dùng phương thức nextInt () hay không
boolean hasNextLine () kiểm tra có dòng khác trong đầu vào của máy quét này hay không
boolean hasNextLong () kiểm tra mã thông báo tiếp theo trong đầu vào của máy quét này có hiểu Long bằng phương thức nextLong () hay không.

Example 1: Read a Line of Text Using Scanner


import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); // takes input from the keyboard String name = input.nextLine(); // prints the name System.out.println("My name is " + name); // closes the scanner input.close(); } }

Output

Enter your name: Kelvin My name is Kelvin

In the above example, notice the line


Scanner input = new Scanner(System.in);

Here, we have created an object of

Scanner

named input.

The

System.in

parameter is used to take input from the standard input. It works just like taking inputs from the keyboard.

We have then used the

nextLine()

method of the

Scanner

class to read a line of text from the user.

Now that you have some idea about

Scanner

, let’s explore more about it.

Java if else using Scanner and String input
Java if else using Scanner and String input

Java Scanner import example

Found in the java.util package, Java’s Scanner class can read input from the command line and return it as a String, BigDecimal or any one of Java’s eight primitive types.

To use the Java Scanner class, you must either:

  • import

    java.util.Scanner
  • import

    java.util.*;
  • reference the package and class name

    java.util.Scanner

    in your code

To use the Java Scanner for user input, either import the java.util package, or use the full package and class name,

java.util.Scanner

.

For the most part, Java’s Scanner class is fairly easy to use, as the methods are largely self-explanatory.

Examples of straightforward Scanner methods to get data such as floats, doubles or text include:


  • nextInt()

  • nextByte()

  • nextLong()

  • nextFloat()

  • nextDouble()

  • nextLine()
  • and just plain

    next()

Java Scanner int example

The following example of Java user input with the Scanner class avoids the use of an import statement:

// Java Scanner int input example System.out.println(“What is your age?”); java.util.Scanner scanner = new java.util.Scanner(System.in); int age = scanner.nextInt(); System.out.println(“I remember being ” + age + ” years old!” ); // Java Scanner String input example System.out.println(“Where were you born?”); String city = scanner.nextLine(); System.out.println(“I hope to visit ” + city + ” some day.” );

This example also demonstrates how to use one instance of the Scanner class multiple times within the same program. You do not need to instantiate it with the new keyword each time.

Java Scanner tutorial with while and for loops
Java Scanner tutorial with while and for loops

Java


import


java.util.Scanner;


public


class


ScannerDemo2 {


public


static


void


main(String[] args)


Scanner sc =


new


Scanner(System.in);


int


sum =


, count =


while


(sc.hasNextInt()) {


int


num = sc.nextInt();


sum += num;


count++;


if


(count >


) {


int


mean = sum / count;


System.out.println(


"Mean: "


+ mean);


else


System.out.println(


"No integers were input. Mean cannot be calculated."


);

Input

1 2 3 4 5

Output

Mean: 3

Important Points About Java Scanner Class

  • To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()
  • To read strings, we use nextLine().
  • To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
  • The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements that have some meaning to the Java compiler. For example, Suppose there is an input string: How are youIn this case, the scanner object will read the entire line and divides the string into tokens: “How”, “are” and “you”. The object then iterates over each token and reads each token using its different methods.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
13 Dec, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Java Scanner

Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.

The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character.

Time for an Example:

Let’s create an example to find a word in the string. Here, we are using indexOf() method that returns an index of the specified substring. See the example below.


public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
int i = str.indexOf(find);
if(i>0)
System.out.println(str.substring(i, i+find.length()));
else
System.out.println("string not found");
}
}

This sentance contains find me string
find me

Java Tutorial: Getting User Input in Java
Java Tutorial: Getting User Input in Java

Example 2

Let’s create another example to find a word in the string. Here, we are using the

contains()

method that returns true, if the specified string is found. See the example below.


public class Main {
public static void main(String[] args){
String str = "This sentance contains find me string";
System.out.println(str);
// find word in String
String find = "find me";
boolean val = str.contains(find);
if(val)
System.out.println("String found: "+find);
else
System.out.println("string not found");
}
}

This sentance contains find me string
String found: find me

How to take String input in Java
Java nextLine() method

The nextLine() method of Scanner class is used to take a string from the user. It is defined in java.util.Scanner class. The nextLine() method reads the text until the end of the line. After reading the line, it throws the cursor to the next line.

The signature of the method is:

The method returns the line that was skipped. It does not accept any parameter. When it does not find any line, then it throws NoSuchElementException. It also throws IllegalStateException if the scanner is closed.

Example of nextLine() method

Output:

Java next() method

Java next() method can read the input before the space id found. It cannot read two words separated by space. It retains the cursor in the same line after reading the input.

The signature of the method is:

The method returns the next complete token from this scanner. It does not accept any parameter. It throws NoSuchElementException if no more tokens are available. It also throws IllegalStateException if the scanner is closed.

Example of next() method

Output:

We can see that whatever we write after Java is skipped by the method and read only the word Java.

Next TopicJava Tutorial

In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.

Using the Scanner class in Java is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming.

Java Scanner hasNext() example

To continually grab input from the user, you can use the Scanner’s

hasNext()

method as the condition for a while loop. This will cause the program to continually take input from the user until the program either shuts down, or encounters a break statement.

Here’s a Scanner

hasNext()

example that adds numbers until the total sum exceeds 100:

System.out.println(“Enter some numbers to add: “); Scanner scanner = new Scanner(System.in); int count = 0; while (scanner.hasNext()) { count = count + scanner.nextInt(); System.out.println(count); if (count > 100) { System.out.println(“Max exceeded!”); break; } }

Java Scanner Input Tutorial - Read String and Primitive Types Input
Java Scanner Input Tutorial – Read String and Primitive Types Input

Example 3: Java Scanner nextDouble()


import java.util.Scanner; class Main { public static void main(String[] args) { // creates an object of Scanner Scanner input = new Scanner(System.in); System.out.print("Enter Double value: "); // reads the double value double value = input.nextDouble(); System.out.println("Using nextDouble(): " + value); input.close(); } }

Output

Enter Double value: 33.33 Using nextDouble(): 33.33

In the above example, we have used the

nextDouble()

method to read a floating-point value.

String user input example

The following example uses the Java Scanner class to take String input from the user:

import java.util.Scanner; public class ScannerUserInput { public static void main(String[] args) { // String input with the Java Scanner System.out.println(“How old are you?”); Scanner stringScanner = new Scanner(System.in); String age = stringScanner.next(); System.out.println(age + ” is a good age to be!”); } }

Console-based interaction with this example looks like this:

How old are you? 50 50 is a good age to be!

Scanner Class Part 4:  Oddity Numbers before Strings (Java)
Scanner Class Part 4: Oddity Numbers before Strings (Java)

Java Scanner Class Constructors

SN Constructor Description
1) Scanner(File source) It constructs a new Scanner that produces values scanned from the specified file.
2) Scanner(File source, String charsetName) It constructs a new Scanner that produces values scanned from the specified file.
3) Scanner(InputStream source) It constructs a new Scanner that produces values scanned from the specified input stream.
4) Scanner(InputStream source, String charsetName) It constructs a new Scanner that produces values scanned from the specified input stream.
5) Scanner(Readable source) It constructs a new Scanner that produces values scanned from the specified source.
6) Scanner(String source) It constructs a new Scanner that produces values scanned from the specified string.
7) Scanner(ReadableByteChannel source) It constructs a new Scanner that produces values scanned from the specified channel.
8) Scanner(ReadableByteChannel source, String charsetName) It constructs a new Scanner that produces values scanned from the specified channel.
9) Scanner(Path source) It constructs a new Scanner that produces values scanned from the specified file.
10) Scanner(Path source, String charsetName) It constructs a new Scanner that produces values scanned from the specified file.

Keywords searched by users: scanning string in java

Categories: Sưu tầm 47 Scanning String In Java

Scanner Class 2 Part 1: Splitting Strings (Java) - Youtube
Scanner Class 2 Part 1: Splitting Strings (Java) – Youtube
Java Programming Ep. 3: Strings & Scanner Input - Youtube
Java Programming Ep. 3: Strings & Scanner Input – Youtube
Java Scanner Input Tutorial - Read String And Primitive Types Input -  Youtube
Java Scanner Input Tutorial – Read String And Primitive Types Input – Youtube
How To Use A Scanner In Netbeans - Java Tutorial - Youtube
How To Use A Scanner In Netbeans – Java Tutorial – Youtube
How To Close A Scanner In Java
How To Close A Scanner In Java
Java If Else Using Scanner And String Input - Youtube
Java If Else Using Scanner And String Input – Youtube
Scanner Class Part 2: Keyboard Input Nextint() And Nextdouble() (Java) -  Youtube
Scanner Class Part 2: Keyboard Input Nextint() And Nextdouble() (Java) – Youtube
Arrays Part 8: The Scanner Class (Java) - Youtube
Arrays Part 8: The Scanner Class (Java) – Youtube
Solved Java Scanner And While Loop Question I Try To | Chegg.Com
Solved Java Scanner And While Loop Question I Try To | Chegg.Com
How To Get User Input In Java Using Scanner Class
How To Get User Input In Java Using Scanner Class
Java 3: Using The Scanner Class In Eclipse - Youtube
Java 3: Using The Scanner Class In Eclipse – Youtube
Reading A String After An Integer - Dev Community
Reading A String After An Integer – Dev Community
Maths And Scanner Class In Java - Pianalytix: Build Real-World Tech Projects
Maths And Scanner Class In Java – Pianalytix: Build Real-World Tech Projects
Scanner Class In Java | Digitalocean
Scanner Class In Java | Digitalocean
Java Read File To String | Digitalocean
Java Read File To String | Digitalocean

See more here: kientrucannam.vn

See more: https://kientrucannam.vn/vn/

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *