Java Scanner class
Scanner class belongs to java.util
package and its primary use is to take user input in java. This class has methods which are used to take input of different data types directly from keyboard or console.
It means that a scanner object can be used to read an integer, character, boolean, double or a string input directly unlike other methods of taking user input in java which always read input as a string and then convert it to the required data type.
This article will explain how to use scanner in java along with examples of different methods of this class.
java.util.Scanner
is widely used for reading user input due to the ease of its object creation and the flexibility it provides when taking input.
A scanner can read input from different sources such as an inputstream, a string, file or console input. It breaks the input read from any of these sources based on a delimiter into tokens and these tokens are then read using various methods.
Default delimiter is a white space but it can be changed with a useDelimiter
method.
Example, if a scanner object reads a string “Learning java scanner”, then it will be broken into tokens “Learning”, “java” and “scanner” which can be read using its next
method.
Java scanner syntax
An object of Scanner
class can be created using its constructor. To read input from keyboard, we need to use the constructor that accepts an inputstream as argument as shown below
Scanner scanner = new Scanner(System.io);
System.in
returns an inputstream that is linked to standard input(keyboard).
Once the scanner is initialized, you can use its methods to read input of different data types. Since scanner class belongs to java.util
package, we need to import scanner before using it.
Before looking at the example of using scanner, first understand its commonly used methods explained below.
Following are the important methods of scanner class.
Method Name | Description | Return Type |
hasNext() |
This method checks if there are any more tokens. | true if there are tokens and false if there is no token left. |
hasNext(String) |
This method checks if there are any more tokens that match the pattern supplied as argument. | true if there are tokens and false if there is no token left. |
next() |
This method returns the next token present in scanner. It throws following exceptions: 1. java.util.NoSuchElementException if there are no tokens available.2. java.lang.IllegalStateException if the scanner is closed before next is called. |
Returns the next token available with scanner as a String. |
next(String) |
This method returns the next token present in scanner if it matches the given pattern. It throws following exceptions: 1. java.util.NoSuchElementException if there are no tokens available.2. java.lang.IllegalStateException if the scanner is closed before next is called. |
Returns the next token that matches the given pattern available with scanner as a String. |
nextLine() |
This method will keep on reading the input till it finds a new line character(enter is pressed). It is used for reading complete lines as user input. It throws following exceptions: 1. java.util.NoSuchElementException if no new line is found.2. java.lang.IllegalStateException if the scanner is closed before nextLine is called. |
Returns the line read from input as a String. |
nextBoolean() |
It reads the next token from input and converts it to a boolean value.It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid boolean . |
boolean value. |
nextByte() |
It reads the next token from input and converts it to a boolean value. It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid Integer. |
Returns a byte . |
nextShort() |
It reads the next token from input and converts it to a short .It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid Integer. |
Returns a short . |
nextInt() |
It reads the next token from input and converts it to a integer value. It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid integer. |
Returns an int . |
nextFloat() |
It reads the next token from input and converts it to a float value.It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid float . |
Returns a float value. |
nextDouble() |
It reads the next token from input and converts it to a double value.1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid double . |
Returns a double value. |
nextLong() |
It reads the next token from input and converts it to a long value.It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid long . |
Returns a long . |
nextBigInteger() |
It reads the next token from input and converts it to a BigInteger value.It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid BigInteger . |
Returns a BigInteger . |
nextBigDecimal() |
It reads the next token from input and converts it to a BigDecimal value.It throws following exceptions: 1. java.util.NoSuchElementException if there is no more token to read.2. java.lang.IllegalStateException if the scanner is closed this method is called.3. java.util.InputMismatchException if the input value is not a valid BigDecimal . |
Returns a BigDecimal . |
useDelimiter(String) |
Changes the scanner’s delimiter to supplied String pattern. | Returns the scanner object itself with the modifier delimiter. |
useDelimiter(Pattern) |
Changes the scanner’s delimiter to supplied String pattern. | Returns the scanner object itself with the modifier delimiter. |
close() |
Closes the scanner. | No return type or void . |
Note: All the next
methods above also have an overloaded version that takes an int
as argument which is the radix to convert the values from String.
Below program shows how java scanner class can be used to read input of multiple types from the user.
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the food item"); // read a single string word String food = scanner.next(); System.out.println("Enter quantity"); // read an integer int quantity = scanner.nextInt(); System.out.println("Enter a comment"); // NOTICE THIS scanner.nextLine(); // read an entire line String comment = scanner.nextLine(); scanner.close(); // display the values read System.out.println("Food: " + food); System.out.println("Quantity: " + quantity); System.out.println("Comment: " + comment); } }
Above program takes as input a single string, an integer and an entire line or multiple word input from the user using its next()
, nextInt()
and nextLine()
methods respectively and then displays the values entered.
nextLine()
method after the nextInt()
method. This is required because the nextInt()
method does not read the next line character and this is done by this nextLine()
method.If a call to
nextLine()
is not written here(that is, if you omit the call to nextLine()
), the scanner will not wait to read the comment
.Output of above program is
Enter the food item
Pizza
Enter quantity
2
Enter a comment
Quality of food is very nice
Food: Pizza
Quantity: 2
Comment: Quality of food is very nice
Close Java scanner
A scanner should be closed after its use with close()
method.
Calling close()
multiple times will close it only once and will not raise any error. Also, using the scanner for any operation after close()
has been called, will raise an IllegalStateException.
Java scanner string input example
Below program creates a scanner with a string as its input rather than reading from console. This example will mainly demonstrate the use of hasNext()
and next()
methods.
import java.util.Scanner; public class ScannerString { public static void main(String[] args) { // create a scanner object Scanner scanner = new Scanner("Learning how to use scanner"); // iterate over tokens while(scanner.hasNext()) { // get the next token String token = scanner.next(); System.out.println(token); } // close scanner scanner.close(); } }
As mentioned earlier, the default delimiter of scanner is a whitespace. Thus, above example creates a scanner with a string as input which consists of multiple words separated by a space.
The scanner breaks its input based on this delimiter and each word becomes its token. We can get these tokens by iterating over the scanner using a while
loop.
In every iteration, scanner checks for the presence on a token with its hasNext
method and returns the token using its next()
method.
Output of above program is
Learning
how
to
use
scanner
Java scanner file input example
A scanner can also be used to read a file. It has a constructor that takes a java.io.File
object as argument which points to a physical file on the system.
Once you create an object of scanner, it can be used to read the file contents using its hasNext()
and next()
methods where hasNext()
will return true
till there is some content to read in the file.
Since the default delimiter is a whitespace, next()
method will return each word that is separated by a space on both sides.
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScannerFileExample { public static void main(String[] args) { try { // create a scanner object Scanner scanner = new Scanner(new File("e:/demo.txt")); // iterate over tokens while(scanner.hasNext()) { // get the next token String token = scanner.next(); System.out.println(token); } // close scanner scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Assuming that the file contents are as below,
It contains different examples.
the output of above program will be
This
is
an
article
about
learning
scanner.
It
contains
different
examples.
Notice that the scanner class constructor that takes a file object as argument throws a java.io.FileNotFoundException
since the file may or may not exist.
You need to catch or throw the exception. This is a part of exception handling concept in java.
Java scanner with modified delimiter
It might also happen that you do not want to split the scanner input into tokens on a whitespace but on a different delimiter.
Below example will show how to use a different delimiter to get tokens from the scanner contents.
import java.util.Scanner; public class ScannerDelimiter { public static void main(String[] args) { // create a scanner object Scanner scanner = new Scanner("Learning##how##to##use##scanner"); // change the delimiter scanner.useDelimiter("##"); // iterate over tokens while(scanner.hasNext()) { // get the next token String token = scanner.next(); System.out.println(token); } // close scanner scanner.close(); } }
Above example changes the scanner’s delimiter to a “##” and tokenizes the content based on this pattern. Output will be
Learning
how
to
use
scanner
If you look carefully, this works similar to split method of String class where a string is divided based on some pattern.
Hope this post was useful for you. Hit the clap if it was helpful.