Scanner class in java

Scanner class belongs to java.util package and its primary use is to take input from user 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 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 on java scanner class will explain its usage along with examples of different methods of this class.


Using scanner in java
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 or a file. 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.
Scanner syntax
For creating an object of scanner class to read input from keyboard, use its constructor that accepts an inputstream as argument. System.in returns an inputstream that is linked to standard input(keyboard) as shown below.

Scanner scanner = new Scanner(System.io);

Once the instance of scanner class is created, you can use its methods to read input of different data types. Before looking at the example of using scanner to read user input, first understand its commonly used methods explained below.


Scanner class methods
Following are the important methods of scanner class.

Method Name Description Return Type
hasNext() This method checks if there are any more tokens. Returns 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. Returns true if there are tokens and false if there is no token left.
next() This method returns the next token present in scanner.
It will throw a java.util.NoSuchElementException if there are no tokens available.
It will throw a 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 will throw a java.util.NoSuchElementException if there are no tokens available.
It will throw a 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 will throw a java.util.NoSuchElementException if no new line is found.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a java.util.InputMismatchException if the input value is not a valid boolean.
Returns a boolean value.
nextByte() It reads the next token from input and converts it to a boolean value.
It will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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.
It will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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 will throw a java.util.NoSuchElementException if there is no more token to read.
It will throw a java.lang.IllegalStateException if the scanner is closed this method is called.
It will throw a 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.


Scanner example program
Below program shows how 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 from the user using its next(), nextInt() and nextLine() methods respectively and then displays the values entered.

Notice the 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


Scanner example with String input
Below program creates a scanner with a string as its input rather than reading from console. This example will mainly demonstrate the usage 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

Scanner example with a file as input
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,

This is an article about learning scanner.
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.
Scanner example 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 to appreciate.

0

Mark Your Impression

Close Menu