Home TechnologyJava Java Scanner Tutorial With Examples

Java Scanner Tutorial With Examples

by Snehashis Mukherjee

On this Java File IO tutorial, you’ll perceive how the Scanner class works with varied examples which you should utilize to your each day Java coding. 

How does a Scanner work?

Principally, a Scanner breaks its enter into tokens utilizing a delimiter sample, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens could be transformed into primitive sorts and Strings utilizing varied subsequent strategies. Right here’s the only instance of utilizing a Scanner to learn an integer quantity from the consumer:

Scanner scanner = new Scanner(System.in);
int quantity = scanner.nextInt();

Let’s perceive find out how to create an occasion of a Scanner and its major strategies. 

How to Initialize a Java Scanner Class?

We are able to create an occasion of the Scanner class to parse a byte enter stream, a personality enter stream or a String, utilizing one of many following constructors (to call a couple of):

  • Scanner(File supply): constructs a Scanner to scan the desired file utilizing the system’s default charset.
  • Scanner(File supply, String charset name): constructs a Scanner to scan the desired file utilizing the desired character set.
  • Scanner(InputStream supply): constructs a Scanner from a byte enter stream utilizing the system’s default charset.
  • Scanner(InputStream supply, String charset name): constructs a Scanner from a byte enter stream utilizing the desired charset.
  • Scanner(Readable supply): constructs a Scanner from a personality stream.
  • Scanner(String supply): constructs a Scanner from a String.

Notice that these constructors throw FileNotFoundException if the desired file doesn’t exist, or IllegalArgumentException if the desired charset will not be discovered. 

Advanced git commands list with a complete tutorial

Java Scanner Methods:

The Scanner class supplies varied strategies for studying tokens from an enter supply. We are able to additionally use totally different delimiter and locale. Listed below are its strategies (to call a couple of):

The hasNext() method returns true if the scanner has one other token in its enter.

The hasNextXXX() method returns true if the subsequent token could be transformed to the desired sort, e.g. the hasNextInt() method returns true if the subsequent token could be transformed to an integer quantity. Listed below are such strategies (to call a couple of):

  • hasNextBoolean()
  • hasNextByte()
  • hasNextDouble()
  • hasNextFloat()

These methods throw InputMismatchException if the subsequent token cannot be transformed to the desired sort; throw NoSuchElementException if the entry is exhausted. And throw IllegalStateException if the scanner is closed. The useDelimiter(String sample)methodology specifies a delimiter totally different than the default whitespace. It’s additionally attainable to make use of an everyday expression as a delimiter for extra superior parsing.

The useLocale(Locale) methodology specifies a locale which is totally different than the system’s default locale. The skip(String pattern) method skips an input that matches the sample. This may be helpful as we don’t need to parse a sure enter. 

Closing the Scanner:

We must always shut the Scanner after use by invoking its close() method. For the reason that Scanner class implements the AutoCloseable interface, we are able to use it with the try-with-resources structure to let the compiler provides the code to shut it implicitly. Next, we present you varied examples utilizing the Scanner class.

1. Using Scanner to Read User’s Input

java scanner nextline, nextInt()

A typical use of Scanner is reading input from the consumer in a command-line environment, as its nextXXX() methods are extra handy than the Console’s readLine() method which returns only String. Right here’s the example:

Scanner scanner = new Scanner(System.in);
System.out.print("What's your name? ");
String name = scanner.next();
System.out.print("How old are you? ");
int age = scanner.nextInt();
System.out.print("What is value of PI? ");
float pi = scanner.nextFloat();
System.out.println("Your name is: " + name);
System.out.println("Your age is: " + age);
System.out.println("Your PI is: " + pi);

Here, we use the Scanner class to read a String, an integer number and a float number.

2. Using Scanner to Read Numbers from File

Scanner scanner = new Scanner(new File("numbers.txt"));
int sum = 0;
while (scanner.hasNextInt()) {
sum += scanner.nextInt();
System.out.println("Sum = " + sum);

Run this code with a file having the following content:

84 90 89 78 54 45 90 2007 443 404 500 1394

And it will print the sum:

Sum = 5278

3. Using Scanner to Read a Text File line by line

nextstring java java scanner(file)

The following code uses the nextLine() method to read a text file line by line, and add all lines to a list of Strings:

Scanner scanner = new Scanner(new File("tasks.txt"));
List<String> listLines = new ArrayList<>();
while (scanner.hasNext()) {
String line = scanner.nextLine();

4. Using Different Delimiter for Scanner

The following code uses the delimiter comma (,) to parse a CSV file:

Scanner scanner = new Scanner(new File("books.csv"));
while (scanner.hasNext()) {
String title = scanner.next();
title = title.trim();   // trim the line terminator character
String author = scanner.next();
float price = scanner.nextFloat();
System.out.format("Title: %s; Author: %s; Price: %.2f%n",
title, author, price);

Given the following CSV file:

Head First Java,Kathy Sierra,23.99,
Effective Java,Joshua Bloch,27.88,
Code Complete,Steve McConnell,38.42,


Title: Head First Java; Author: Kathy Sierra; Price: 23.99
Title: Effective Java; Author: Joshua Bloch; Price: 27.88
Title: Code Complete; Author: Steve McConnell; Price: 38.42

5. Using Regular Expressions for Scanner

In the following code, we use regular expressions to find only Strings containing the world ‘Java’:

Scanner scanner = new Scanner(new File("books.txt"));
String pattern = ".*Java.*";
while (scanner.hasNext()) {
if (scanner.hasNext(pattern)) {
String javaBook = scanner.next(pattern);
} else {

Here, we use a regular expression for the delimiter: [\r\n] meaning that the delimiter is new line character (either \r or \n); and the regular expression .*Java.* is to check if the input contains the word ‘Java’.Given the following text file:

Thinking in Java
The Passionate Programmer
Head First Java
Effective Java
Code Complete
Core Java Programming


Thinking in Java
Head First Java
Effective Java
Core Java Programming

6. Using Different Locale for Scanner

The following code uses a Scanner with French locale to parse numbers from a text file:

Scanner scanner = new Scanner(new File("FrenchNumbers.txt"));
while (scanner.hasNextDouble()) {
double number = scanner.nextDouble();

Given the following text file (in French locale):


It gives the following output (in US locale):


API References:

Scanner class Javadoc

Related Posts


AskerZer June 5, 2020 - 7:40 PM

https://fedorovkarb.online – ACADEMIC WRITING NEVER BEEN EASIER
Every academic writing dilemma can be solved! We write all types of papers in different subject areas from scratch.

This is display.cgi ( July 8, 2020 - 1:27 AM

Your style is unique compared to other people
I have read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this site.

backlinks July 8, 2020 - 10:19 AM

Great article, totally what I needed.

website promotion in TOP July 14, 2020 - 5:15 AM

Definitely believe that which you stated. Your favourite justification appeared to be at
the net the simplest thing to remember of.
I say to you, I definitely get annoyed at the same time as
other people think about concerns that they just do not recognize about.
You controlled to hit the nail upon the top and also
outlined out the whole thing without having side-effects , other folks could take a signal.
Will probably be again to get more. Thanks

find someone to write my college paper July 14, 2020 - 12:02 PM

Hi everyone, it’s my first pay a quick visit at this site, and paragraph is actually fruitful designed for me, keep up posting these
types of articles or reviews.


Leave a Comment