что такое 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 — примеры и методы
Это руководство по посвящено использованию класса Scanner в Java пакета java.util. Мы будем показывать базовое применение класса Scanner до самых расширенных функций этого класса, используя примеры.
Класс Scanner имеет богатый набор API, который обычно используется для разбиения входных данных конструктора Scanner на токены. Входные данные разбиваются на токены с помощью разделителя, определенного в классе Scanner с использованием метода radix, или могут быть определены.
Объявление:
public final class Scanner
extends Object
implements Iterator, Closeable
Конструкторы класса Scanner – public Scanner(Readable source)
Создает новый сканер, который создает значения, отсканированные из указанного источника.
Параметры: source – источник символов, реализующий интерфейс Readable
Не путайте с типом объекта, доступным для чтения в качестве параметра конструктора. Readable – это интерфейс, который был реализован с помощью BufferedReader, CharArrayReader, CharBuffer, FileReader, FilterReader, InputStreamReader, LineNumberReader, PipedReader, PushbackReader, Reader, StringReader.
Это означает, что мы можем использовать любой из этих классов в Java при создании экземпляра объекта Scanner.
public Scanner(InputStream source)
Создает новый сканер, который создает значения, отсканированные из указанного входного потока. Байты из потока преобразуются в символы с использованием кодировки по умолчанию базовой платформы.
Параметры: источник – входной поток для сканирования.
Метод ввода этого конструктора – InputStream. Класс InputStream является одним из классов верхнего уровня в пакете java.io, и его использование будет проблемой.
Однако мы можем использовать подклассы InputStream, как показано ниже. Мы использовали FileInputStream, поскольку он является подклассом InputStream, при его включении проблем не возникнет.
public Scanner(File source) выдает исключение FileNotFoundException
Байты из файла преобразуются в символы с кодировкой по умолчанию базовой платформы.
Параметры: источник – файл для сканирования
Этот конструктор очень прост. Просто требует источник файла. Единственной целью этого конструктора является создание экземпляра объекта Scanner для сканирования через файл.
public Scanner(Path source) throws IOException
источник – путь к файлу для сканирования. Для параметра конструктора требуется источник Path, который используется редко.
public Scanner(String source)
Создает новый сканер, который выдает значения, отсканированные из указанной строки.
Источник – строка для сканирования.
Этот конструктор может быть самым простым на практике, поскольку для него требуется только строковый параметр, и он строго используется для сканирования ввода строки.
Scanner в Java для чтения файлов
Считать файл очень легко, используя класс Scanner. Нам просто нужно объявить это с помощью конструктора Scanner, например:
Хитрость в итерации по токену Scanner состоит в том, чтобы применять те методы, которые начинаются с hasNext, hasNextInt и т.д. Давайте сначала остановимся на чтении файла построчно.
В приведенном выше фрагменте кода мы использовали флаг scan.hasNextLine() как средство проверки наличия токена, который в этом примере доступен на входе сканера. Метод nextLine() возвращает текущий токен и переходит к следующему.
Комбинации hasNextLine() и nextLine() широко используются для получения всех токенов на входе сканера. После этого мы вызываем метод close(), чтобы закрыть объект и тем самым избежать утечки памяти.
Считать строку из консоли ввода, используя Scanner Class
Класс Scanner принимает также InputStream для одного из своих конструкторов. Таким образом, ввод можно сделать с помощью:
После помещения в наш объект сканера, у нас теперь есть доступ к читаемому и конвертируемому потоку, что означает, что мы можем манипулировать или разбивать входные данные на токены. Используя богатый набор API сканера, мы можем читать токены в зависимости от разделителя, который мы хотим использовать в конкретном типе данных.
Важные советы
Недавно я обнаружил одну проблему. Допустим, что мы просим пользователя ввести идентификатор сотрудника и имя сотрудника из консоли.
После чего мы будем читать ввод с консоли, используя сканер. Идентификатор сотрудника будет читаться с nextInt(), а имя сотрудника будет читаться как nextLine(). Это довольно просто, но это не сработает.
Приведенный выше пример не будет работать, потому что метод nextInt не читает последний символ новой строки вашего ввода и, следовательно, эта новая строка используется при следующем вызове nextLine.
Чтобы решить эту проблему, просто используйте next вместо nextline, но если вы хотите указать только nextLine, добавьте еще один scan.nextLine() после nextInt. Посмотрите ниже фрагмент кода:
Список методов java.util.Scanner
Ниже приведен список методов java.util.Scanner, которые мы можем использовать для сложного анализа ввода.
return | метод | Описание |
---|---|---|
void | close() | Закрывает объект сканера. |
Pattern | delimiter() | Возвращает шаблон, который объект Scanner в настоящее время использует для сопоставления разделителей. |
String | findInLine(Pattern pattern) | Этот метод возвращает объект String, который удовлетворяет объекту Pattern, указанному в качестве аргумента метода. |
String | findInLine(String pattern) | Пытается найти следующее вхождение шаблона, созданного из указанной строки, игнорируя разделители. |
String | findWithinHorizon(Pattern pattern, int horizon) | Ищет следующее вхождение указанного шаблона. |
String | findWithinHorizon(String pattern, int horizon) | Ищет следующее вхождение шаблона ввода, игнорируя разделитель |
boolean | hasNext() | Возвращает true, если у этого сканера есть другой токен на входе. |
boolean | hasNext(Pattern pattern) | Возвращает true, если следующий полный токен соответствует указанному шаблону. |
boolean | hasNext(String pattern) | Возвращает true, если следующий токен соответствует шаблону, созданному из указанной строки. |
boolean | hasNextBigDecimal() | Возвращает true, если следующий токен на входе этого сканера можно интерпретировать как BigDecimal с помощью метода nextBigDecimal(). |
boolean | hasNextBigInteger() | Возвращает true, если следующий токен на входе этого сканера может быть интерпретирован как BigInteger, по умолчанию с использованием метода nextBigInteger(). |
boolean | hasNextBigInteger(int radix) | аналогично методу выше, но в указанном основании с помощью метода nextBigInteger() |
boolean | hasNextBoolean() | проверяет, имеет ли объект логический тип данных в своем буфере. |
boolean | hasNextByte() | возвращает значение true, если следующий байт в буфере сканера можно преобразовать в тип данных байта, в противном случае – значение false. |
boolean | hasNextByte(int radix) | true, если следующий токен на входе этого сканера может быть интерпретирован как значение байта в указанном основании с помощью метода nextByte(). |
boolean | hasNextDouble() | true, если следующий токен на входе этого сканера можно интерпретировать как двойное значение с помощью метода nextDouble(). |
boolean | hasNextFloat() | аналогично методу выше, но как значение с плавающей запятой, используя nextFloat(). |
boolean | hasNextInt() | true, если следующий токен на входе этого сканера можно интерпретировать как значение int по умолчанию с помощью метода nextInt(). |
boolean | hasNextInt(int radix) | возвращает логическое значение true, если маркер можно интерпретировать как тип данных int относительно radix, используемого объектом сканера, в противном случае – false. |
boolean | hasNextLine() | возвращает логический тип данных, который соответствует новой строке String, которую содержит объект Scanner. |
boolean | hasNextLong() | Возвращает true, если следующий токен на входе этого сканера может быть интерпретирован как длинное значение по умолчанию с использованием метода nextLong(). |
boolean | hasNextLong(int radix) | аналогично методу выше, но в указанном основании с помощью метода nextLong (). |
boolean | hasNextShort() | как короткое значение с использованием метода nextShort(). |
boolean | hasNextShort(int radix) | возвращает логическое значение true, если маркер можно интерпретировать как короткий тип данных относительно radix, используемого объектом сканера, в противном случае – false. |
IOException | ioException() | Возвращает IOException, последний раз выданный в основе сканера Readable. |
Locale | locale() | возвращает Locale |
MatchResult | match() | возвращает объект MatchResult, который соответствует результату последней операции с объектом. |
String | next() | Находит и возвращает следующий полный токен. |
String | next(Pattern pattern) | Возвращает следующий токен, если он соответствует указанному шаблону. |
String | next(String pattern) | Возвращает следующий токен, если он соответствует шаблону, созданному из указанной строки. |
BigDecimal | nextBigDecimal() | Сканирует следующий токен ввода как BigDecimal. |
BigInteger | nextBigInteger() | как BigInteger. |
BigInteger | nextBigInteger(int radix) | как BigInteger. |
boolean | nextBoolean() | Сканирует следующий токен ввода как логическое значение и возвращает его. |
byte | nextByte() | как byte. |
byte | nextByte(int radix) | как byte. |
double | nextDouble() | double. |
float | nextFloat() | float. |
int | nextInt() | int. |
int | nextInt(int radix) | int. |
String | nextLine() | Перемещает сканер за текущую строку и возвращает пропущенный ввод. |
long | nextLong() | long. |
long | nextLong(int radix) | long. |
short | nextShort() | short. |
short | nextShort(int radix) | short. |
int | radix() | Возвращает основание сканера по умолчанию. |
void | remove() | Операция удаления не поддерживается данной реализацией Iterator. |
Scanner | reset() | Сбрасывает |
Scanner | skip(Pattern pattern) | Пропускает ввод, соответствующий указанному шаблону, игнорируя разделители. |
Scanner | skip(String pattern) | Пропускает ввод, соответствующий шаблону, созданному из указанной строки. |
String | toString() | Возвращает строковое представление |
Scanner | useDelimiter(Pattern pattern) | Устанавливает шаблон ограничения этого сканера в указанный шаблон. |
Scanner | useDelimiter(String pattern) | как метод выше, но созданный из указанной строки. |
Scanner | useLocale(Locale locale) | устанавливает local в указанный local. |
Scanner | useRadix(int radix) | Устанавливает radix равным указанному. |
Средняя оценка / 5. Количество голосов:
Как работать с классом Scanner в Java: примеры
С помощью класса java.util.Scanner можно анализировать простые типы данных и строки. Этот класс принимает данные из файлов, потоков, строк, последовательностей символов или байтов.
Входные данные разбиваются на токены. По умолчанию разделителем токенов служит пробел, но его можно заменить строкой ( java.lang.String ) или регулярным выражением ( java.util.regex.Pattern ).
Давайте рассмотрим конструкторы этого класса по порядку.
Конструктор public Scanner(Readable source)
Вот как это делается с помощью класса FileReader :
Конструктор public Scanner(InputStream source)
Этот конструктор создает сканер, с помощью которого можно получить значения из указанного входного потока. Байты из такого потока преобразуются в символы (с использованием набора символов по умолчанию для базовой платформы).
Также есть вариант конструктора, который позволяет получать значения из входного потока, преобразовывая байты в символы с использованием набора символов, указанного пользователем:
public Scanner(InputStream source, String charsetName)
Например, для потока стандартного ввода он объявляется просто:
Scanner scanner = new Scanner(System.in)
Конструктор public Scanner(File source) throws FileNotFoundException
Чтобы использовать произвольный набор символов, укажите его во втором аргументе:
public Scanner(File source, String charsetName) throws FileNotFoundException
Scanner scanner = new Scanner(new File(«D:\Scanner.txt»));
Конструктор public Scanner(Path source) throws IOException
Для использования другого набора символов укажите его во втором аргументе:
public Scanner(Path source, String charsetName) throws IOException
Давайте создадим сканер с помощью пути:
Конструктор public Scanner(String source)
Создает сканер, который позволяет получать значения из указанной строки:
Scanner scanner = new Scanner(«Parse me»);
Как прочитать файл с помощью класса Scanner
Как прочитать ввод из консоли с помощью класса Scanner
Чтобы прочитать данные из консоли, создадим входной поток System.in и используем метод nextLine() :
Методы класса Scanner
Тип возврата | Метод | Описание |
void | close() | Закрывает объект сканера. |
Pattern | delimiter() | Возвращает шаблон, который объект Scanner в настоящее время использует для сопоставления разделителей. |
String | findlnLine(Pattern pattern) | Этот метод возвращает объект String, который удовлетворяет объекту Pattern, указанному в качестве аргумента метода. |
String | findlnLine(String pattern) | Пытается найти следующее вхождение шаблона, созданного из указанной строки, игнорируя разделители. |
String | findWithinHorizon(Pattern pattern, int horizon) | Ищет следующее вхождение указанного шаблона. |
String | findWithinHorizon(String pattern, int horizon) | Ищет следующее вхождение шаблона ввода, игнорируя разделитель |
boolean | hasNext() | Возвращает true, если у этого сканера есть другой токен на входе. |
boolean | hasNext(Pattern pattern) | Возвращает true, если следующий полный токен соответствует указанному шаблону. |
boolean | hasNext(String pattern) | Возвращает true, если следующий токен соответствует шаблону, созданному из указанной строки. |
boolean | hasNextBig Decimal() | Возвращает true, если следующий токен на входе этого сканера можно интерпретировать как BigDecimal с помощью метода nextBigDecimal(). |
Подробнее о сканере можно прочитать на сайте документации по Java.
Работа со сканером в Java (ввод и вывод данных)
Предлагаем вспомнить 2 примера из жизни, которые как нельзя кстати будут для изучения данной темы.
Чем то схожие задачи есть и в мире программирования на Java. Например, часто необходимо выполнить такие задачи:
Итак, рассмотрим несколько примеров кода, после которых Вы:
Что такое 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.
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
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 :: |
| |||
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][-+]?6+)? | |||
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
Modifier and Type | Method and Description |
---|---|
void | close() |
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.