Что такое scanner в java

Класс Scanner в Java: Описание, методы, примеры

Scanner это класс в языке Java, который позволяет считывать данные из разных источников. В том числе и с консоли. Сегодня я хочу описать принципы его работы и показать на примере как можно прочитать ввод юзера в Java программу.

Класс сканер был создан для чтения данных из входящих потоков. Это может быть консоль приложения, файл и т.д.

Давайте теперь посмотрим, как его можно использовать чтобы считать пользовательский ввод с консоли и подать данные в программу.

Допустим у нас есть приложение при котором юзеру сначала нужно ввести цифры, а потом текст. Вот что получилось у меня:

В результате запуска приложения:

Как видите, код довольно простой. Чтобы вызвать методы класса Scanner нужно всего лишь написать Scanner scanner = new Scanner(System.in);

Внутри скобок (System.in); я передал систем ин так как хочу чтобы мой сканер считывал данные из консоли.

Чтобы считать данные из файла достаточно передать в скобки new File(“путь_к_файлу”).

В корне проекта я создал текстовый файл test.txt с содержимым:

Вот моя программа, которая считывает строку из файла с помощью класса Scanner:

Если нужно считать из файла больше чем одну строку, то тут уже не обойтись без циклов. Если Вы еще не знакомы с этим понятием — эту часть статьи можно пропустить и приступить к ней после изучения циклов.

В класс Scanner есть метод hasNextLine(), который возвращает true/false в зависимости от того есть ли еще строки в файле. Используя этот метод и цикл можно считать весь файл строка за строкой:

Мой исходный текстовый файл:

А вот результат работы приложения:

Причем программу выше можно немного оптимизировать и добавлять прочитанные строки к одной строке а потом можно вывести все целиком. Или можно как-то обработать строку в дальнейшем.

Это все что я хотел рассказать о классе Scanner. Он станет для Вас удобным инструментом для считывания данных с консоли или файла чтобы писать базовые интерактивные приложения на языке Java.

Я намеренно не стал рассказывать об остальных методах сканера, так как думаю что для новичков этого будет достаточно. Все остальное сможете посмотреть при непосредственном использовании Scanner.

Источник

Что такое scanner в java

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:

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

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

prints the following output:

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

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.

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 useRadix(int) method. The reset() method will reset the value of the scanner’s radix to 10 regardless of whether it was previously changed.

Localized numbers

An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner’s locale. A scanner’s initial locale is the value returned by the 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.

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

LocalGroupSeparatorThe character used to separate thousands groups, i.e., dfs. getGroupingSeparator()
LocalDecimalSeparatorThe character used for the decimal point, i.e., dfs. getDecimalSeparator()
LocalPositivePrefixThe string that appears before a positive number (may be empty), i.e., df. getPositivePrefix()
LocalPositiveSuffixThe string that appears after a positive number (may be empty), i.e., df. getPositiveSuffix()
LocalNegativePrefixThe string that appears before a negative number (may be empty), i.e., df. getNegativePrefix()
LocalNegativeSuffixThe string that appears after a negative number (may be empty), i.e., df. getNegativeSuffix()
LocalNaNThe string that represents not-a-number for floating-point values, i.e., dfs. getNaN()
LocalInfinityThe string that represents infinity for floating-point values, i.e., dfs. getInfinity()

Number syntax

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

NonASCIIDigit ::= A non-ASCII character c for which Character.isDigit (c) returns true
Non0Digit ::= [1-Rmax] | NonASCIIDigit
Digit ::= [0-Rmax] | NonASCIIDigit
GroupedNumeral ::
= (Non0Digit Digit? Digit?
( LocalGroupSeparator Digit Digit Digit )+ )
Numeral ::= ( ( Digit+ ) | GroupedNumeral )
Integer ::= ( [-+]? ( Numeral ) )
| LocalPositivePrefix Numeral LocalPositiveSuffix
| LocalNegativePrefix Numeral LocalNegativeSuffix
DecimalNumeral ::= Numeral
| Numeral LocalDecimalSeparator Digit*
| LocalDecimalSeparator Digit+
Exponent ::= ( [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][-+]?2+)?
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 Summary

Method Summary

Methods

Modifier and TypeMethod and Description
voidclose()

Methods inherited from class java.lang.Object

Constructor Detail

Scanner

Scanner

Scanner

Scanner

Scanner

Scanner

Scanner

Scanner

Scanner

Scanner

Method Detail

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.

ioException

delimiter

useDelimiter

useDelimiter

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.

locale

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

useLocale

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.

radix

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

useRadix

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

match

toString

hasNext

remove

hasNext

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

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

hasNext

hasNextLine

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.

findInLine

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

findInLine

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.

findWithinHorizon

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

findWithinHorizon

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 negative, then an IllegalArgumentException is thrown.

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.

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

hasNextBoolean

nextBoolean

hasNextByte

hasNextByte

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.

nextByte

hasNextShort

hasNextShort

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.

nextShort

hasNextInt

hasNextInt

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.

nextInt

hasNextLong

hasNextLong

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.

nextLong

hasNextFloat

nextFloat

hasNextDouble

nextDouble

hasNextBigInteger

hasNextBigInteger

nextBigInteger

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.

nextBigInteger

hasNextBigDecimal

nextBigDecimal

reset

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

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 в java

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 :

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

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

prints the following output:

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

A scanning operation may block waiting for input.

The next() and hasNext() methods and their 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 tokens() method may also block waiting for input.

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 read() method throws an IOException then the scanner assumes that the end of the input has been reached. The most recent IOException thrown by the underlying readable can be retrieved via the ioException() method.

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

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

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

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

Localized numbers

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

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

Whitespace is not significant in the above regular expressions.

Источник

Работа со сканером в Java (ввод и вывод данных)

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в javaЧто такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в javaЧто такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в javaЧто такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в javaЧто такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в javaЧто такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

Предлагаем вспомнить 2 примера из жизни, которые как нельзя кстати будут для изучения данной темы.

Чем то схожие задачи есть и в мире программирования на Java. Например, часто необходимо выполнить такие задачи:

Итак, рассмотрим несколько примеров кода, после которых Вы:

Источник

Ввод с клавиатуры

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

Что такое scanner в java. Смотреть фото Что такое scanner в java. Смотреть картинку Что такое scanner в java. Картинка про Что такое scanner в java. Фото Что такое scanner в java

1. Чтение с консоли, System.in

Но, как вы уже наверное догадываетесь, одного вывода на экран недостаточно. Цель большинства программ — сделать что-то полезное для пользователя. Поэтому очень часто нужно, чтобы пользователь мог вводить данные с клавиатуры.

Поэтому мы воспользуемся еще одним классом, который в паре с объектом System.in даст нам все, что нужно. В Java уже давно есть классы на все случаи жизни. С одним из них мы сейчас и познакомимся.

2. Класс Scanner

Класс Scanner (полное имя java.util.Scanner ) умеет считывать данные из разных источников: консоль, файлы, интернет. Если мы хотим, чтобы он считывал данные с клавиатуры, мы должны передать ему объект System.in в качестве параметра – источника данных. А уж объект типа Scanner сам разберется, что с ним делать.

Считывание с клавиатуры с помощью объекта типа Scanner будет выглядеть примерно так:

Выглядит вроде несложно, но так ли все просто на самом деле?

Думаю, у вас появилась куча вопросов, и сейчас мы на них ответим.

Но для начала продемонстрируем пример полной программы, где используется класс Scanner :

3. Создание объекта Scanner

Такая строка может сбивать с толку, однако вы будете постоянно встречать похожие вещи. Так что, думаем, настало время объяснить, что тут написано.

Вспомним, как мы обычно создаем переменную с текстом:

Сначала мы пишем тип переменной ( String ), затем ее имя ( str ) и, наконец, после знака равно пишем значение.

В нашей странной строке на самом деле все то же самое:

Думаю, теперь все стало гораздо понятнее.

4. Вызов методов

Чтобы вызвать методы объекта, на который ссылается переменная, нужно после имени переменной написать точку, а затем имя метода и параметры. Общий вид этой команды такой:

Если вы не планируете передавать в функцию параметры, нужно писать просто пустые скобки:

5. Ввод данных с консоли

Если пользователь ввел данные, которые невозможно преобразовать в целое число, в программе возникнет ошибка, и она завершится.

Пример программы, которая считывает с клавиатуры два числа и выводит их сумму:

6. Другие методы класса Scanner

МетодОписание
Считывает данные и преобразует их в тип byte
Считывает данные и преобразует их в тип short
Считывает данные и преобразует их в тип int
Считывает данные и преобразует их в тип long
Считывает данные и преобразует их в тип float
Считывает данные и преобразует их в тип double
Считывает данные и преобразует их в тип boolean
Считывает одно «слово». Слова разделяются пробелами или enter
Считывает целую строку

Есть еще методы, которые позволяют проверить тип еще не считанных данных (чтобы знать, каким методом их считывать).

7. Ввод данных из строки

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *