Last Updated:

Scanner Class in Java - Description and Example

scanner in java
 
We continue the series of articles for beginners with material about the Scanner class. Let's make a brief overview and look at the example of the most used methods.

A Brief Overview of the Scanner Class in Java

 

The class is used to retrieve (read) user input in the form of String, , , , , , .Scannerbyteshortintlongfloatdouble

The scanner searches for tokens in the input string.

A token (or token) is a series of numeric or alphanumeric characters that ends with a separator. The delimiter can be a tab character, a carriage return (line feed or simply 'Enter'), the end of a file, or a space.

 

Example: if a user entered a series of numbers with spaces between each number, the Scanner class will accept all numbers as a separate token. In this case, the space characters act as delimiters.

Example of using Scanner in Java

The Scanner class is provided with many constructors, for example:

The second constructor throws .FileNotFoundException

Let's look at academic examples of working with each of them:

1). Read the primitive data types and the string:

Note that when reading and can be discarded. This indicates that a value was entered that was not recognized as or .floatdoubleInputMismatchExceptionfloatdouble

Why? It's all about the locale, or more precisely, the sign that separates the whole part from the remainder. In our case, we entered a semicolon: and there were no problems, but trying to enter such a value: will lead to the above error.1,231.23

 

How can I avoid this? 

 

Just specify the locale for Scanner:

And now you can read and values with a period in the form of 1.231.floatdouble

Also, the situation with can be avoided using the following methods:InputMismatchException

  • boolean hasNextLine(): will return if the scanner has the following input string, otherwise — truefalse;
  • boolean hasNextInt(): returns if the next scanner token is a value of type trueint;
  • boolean hasNextFloat(): returns if the next scanner token is a value of type truefloat;

2). The second academic example is the processing of a file using Scanner

It has two methods for reading data:

  • .hasNext();
  • .hasNextLine();

They return if there is still a token in the file.true

As you can see, the Scanner class is very convenient for processing various sources of information – whether they are files, input streams or strings.