Как использовать scanner в java
Перейти к содержимому

Как использовать scanner в java

  • автор:

Use Scanner in Java correctly

There are so many ways to process with standard I/O or files. But using scanner is useful for breaking down input into tokens and translating token according to their data type.

But actually, using Scanner has many problems. It can cause your problem make action wrong, not perform following your intention. In this article, we will find the pros and cons when using scanner to avoid them.

Table of Contents

Introduction about Scanner class

Scanner is a class in java.util package that is used to get input from standard I/O or files with primitives types such as int, double, strings, …

A simpler text scanner which can parse primitive types and strings using regular expression. A Scanner breaks its input into tokens using delimiter pattern, which by default matches whitespace (includes tabs, blanks, and line terminators). The resulting tokens may then be converted into values of differents types using the various next() methods.

To create an object of Scanner class, you can reference to Constructors in link Scanner in documetation of Oracle. Normally, you can pass the object of standard I/O such as System.in or object of File class to read input from a file. Or you can get information from string based on the pattern (refer the below example). It means that Scanner class can accept to read input from different sources.

To read values such as byte, short, int, long, float, double, boolean, big integer, big decimal, you only can call the method nextABC() with ABC is one of the data types that you need.

To check the data type of value that you have just been scanned, use hasNextABC() method.

To read strings, use nextLine();

To read single character, use next().charAt(0);

To use a different separator, call useDelimiter() method, specifying a regular expression.

Even though a scanner is not a stream, you need to close it to indicate that you’re done with its underlying stream. Note that: when a scanner is closed, it will close its input source if the source implements the Closeable interface.

Passing a null parameter into any method of a Scanner will cause a NullPointerException to be thrown.

Problem with Scanner class

When you call nextABC() method with ABC is int, long, …, before calling nextLine() method. The result is that you can not receive a string that you have just been typed.

So What is your problem at here?

Because, when you type an integer and then end of typing, you will touch “\n” (Enter key). The variable n will receive that value. But enter key is still on the buffer System.in. So when you call nextLine() method, this method will get enter key, and out of keyboard state. So string s have no value.

Solution for this problem:

    Using next() method to discard the newline character.

Using the other stream I/O such as BufferReader, …

Benefits and Drawbacks

  • Using Scanner will help us parse, convert to our desired data type without implementing ourself.
  • We can customize separator in Scanner to get what we want.
  • Scanner has a little buffer (1KB char buffer).
  • Scanner is slower than BufferReader because Scanner does parsing of input data, and BufferReader simply reads sequence of characters.
  • A Scanner is not safe for multithreaded use without external synchronization.

How Scanner works

Initialization of Scanner class’s object

Scanner class will contain only a source as character stream by using InputStreamReader, or Channels class.

Some patterns for identifying primitive data types

Using buffer to contain the input’s data and a cache for the last few recently used Patterns

Scanner class uses CharBuffer data type to save the input’s data. And it utilizes LRU cache pattern to save the used Patterns for some primitive data types.

To extract data from each line, Scanner class uses regular expression with the buffer’s data by using Matcher class.

It means that it takes resources such as memory, CPU to process each line.

How nextLine() method implements

First thing, Scanner class use findPatternInBuffer() method to check whether the length of buffer is enoung or not. If not, it will set a variable needInput to true to read file continuously.

Sencond thing, if the content in buffer is enough, so we only need to extract data from it. Otherwise, reading data from the InputStream, then put into buffer.

Final thing, after receiving result from findWithinHorizon() method, we need to subtract to the length of separator string to get the real result.

Wrapping up

Understanding about how Scanner works — using regular expression for separator between tokens, and idenfifying them as our primitive data type.

Everything You Need to Know About Scanner Class in Java

upGrad

Anyone who works with the Java programming language is well aware of Scanner class in Java. And for aspiring Java Developers who don’t know what Scanner class is and how to use Scanner class in Java, this article is the perfect introduction to it.

In this post, we’ll engage in a detailed discussion of Scanner class in Java, its different methods, and how they function. So, if you are looking forward to knowing more about Scanner class in Java, keep reading till the end!

What is the Scanner class in Java?

The Scanner class in Java is primarily used to obtain user input. The java.util package contains it. The Scanner class not only extends Object class, but it can also implement Iterator and Closeable interfaces. It fragments the user input into tokens using a delimiter, which is by default, whitespace.

It is pretty easy to use the Scanner class — first, you create an object of the class and then use any of the available methods present in the Scanner class documentation.

Besides being one of the simplest ways of obtaining user input data, the Scanner class is extensively used to parse text for strings and primitive types by using a regular expression. For instance, you can use Scanner class to get input for different primitive types like int, long, double, byte, float, and short, to name a few.

You can declare Java Scanner class like so:

public final class Scanner

extends Object

implements Iterator<String>

If you wish to obtain the instance of the Scanner class that reads user input, you have to pass the input stream (System.in) in the constructor of Scanner class, as follows:

Scanner in = new Scanner(“Hello upGrad”);

What are the different Scanner class constructors?

Here are the six commonly used Scanner class constructors:

  1. Scanner(File source) — It creates a new Scanner to generate values scanned from a particular file.
  2. Scanner(InputStream source) — It creates a new Scanner to produce values scanned from a specified input stream.
  3. Scanner(Readable source) — It creates a new Scanner to deliver values scanned from a specified source.
  4. Scanner(String source) — It creates a new Scanner to produce values scanned from a particular string.
  5. Scanner(ReadableByteChannel source) — It creates a new Scanner to produce values scanned from a specified channel.
  6. Scanner(Path source) — It creates a new Scanner to generate values scanned from a specified file.

What are the different Scanner class methods?

Just like Scanner class constructors, there’s also a comprehensive suite of Scanner class methods, each serving a unique purpose. You can use the Scanner class methods for different data types. Below is a list of the most widely used Scanner class methods:

  1. void [close()] — This method is used to close the scanner.
  2. pattern [delimiter()] — This method helps to get the Pattern that is currently being used by the Scanner class to match delimiters.
  3. Stream<MatchResult> [findAll()] — It gives a stream of match results that match the specified pattern string.
  4. String [findInLine()] — It helps to find the next occurrence of a pattern created from a specified string. This method does not consider delimiters.
  5. String [nextLine()] — It is used to get the input string that was skipped of the Scanner object.
  6. IOException [ioException()] — This method helps to obtain the IOException last projected by the Scanner’s readable.
  7. Locale [locale()] — It fetches a Locale of the Scanner class.
  8. MatchResult [match()] — It offers the match result of the last scanning operation performed by the Scanner.
  9. BigDecimal [nextBigDecimal()] — This method is used to scan the next token of the input as a BigDecimal.
  10. BigInteger [nextBigInteger()] — This method scans the next token of the input as a BigInteger.
  11. byte [nextByte()] — It scans the next token of the user input as a byte value.
  12. double [nextDouble()] — It scans the next token of the user input as a double value.
  13. float [nextFloat()] — This method scans the next token of the input as a float value.
  14. int [nextInt()] — This method is used to scan the next token of the input as an Int value.
  15. boolean:
  • [hasNext()] — This method returns true if the Scanner has another token in the user input.
  • [hasNextBigDecimal()] — This method checks if the next token in the Scanner’s input can be interpreted as a BigDecimal by using the nextBigDecimal() method.
  • [hasNextBoolean()] — It checks if the next token in the Scanner’s input can be interpreted as a Boolean using the nextBoolean() method.
  • [hasNextByte()] — It checks whether or not the next token in the Scanner’s input is interpretable as a Byte using the nextBigDecimal() method.
  • [hasNextFloat()] — It checks whether or not the next token in the Scanner’s input is interpretable as a Float using the nextFloat() method.
  • [hasNextInt()] — It checks whether or not the next token in the Scanner’s input is interpretable as an Int using the nextInt() method.

How to use Scanner class in Java?

As we mentioned before, using the Scanner class in Java is quite easy. Below is an example demonstrating how to implement Scanner class using the nextLine() method:

import java.util.*;

public class ScannerExample <

public static void main(String args[])<

Scanner in = new Scanner(System.in);

System.out.print(“Enter your name: “);

String name = in.nextLine();

System.out.println(“Name is: “ + name);

If you run this program, it will deliver the following output:

Enter your name: John Hanks

Name is: John Hanks

Wrapping up

This article covers the fundamentals of the Scanner class in Java. If you acquaint yourself with the Scanner class constructs and methods, with time and continual practice, you will master the craft of how to use Scanner class in Java programs.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Class Scanner

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:

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 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.

The findInLine() , findWithinHorizon() , skip() , and findAll() 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 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.

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 .

Использование класса 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 равным указанному.

Средняя оценка 4.1 / 5. Количество голосов: 23

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

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

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