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);
 
scanner.close();

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();
}
 
scanner.close();
 
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();
listLines.add(line);
}
 
System.out.println(listLines);
scanner.close();

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"));
scanner.useDelimiter(",");
 
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);
}
 
scanner.close();

Given the following CSV file:

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

output:

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"));
scanner.useDelimiter("[\r\n]");
 
String pattern = ".*Java.*";
 
while (scanner.hasNext()) {
if (scanner.hasNext(pattern)) {
String javaBook = scanner.next(pattern);
System.out.println(javaBook);
} else {
scanner.next();
}
}
 
scanner.close();

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

output:

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"));
scanner.useLocale(Locale.FRENCH);
 
while (scanner.hasNextDouble()) {
double number = scanner.nextDouble();
System.out.println(number);
}
 
scanner.close();

Given the following text file (in French locale):

123,5  
456,89 
200,99 
318,12

It gives the following output (in US locale):

123.5
456.89
200.99
318.12

API References:

Scanner class Javadoc

Related Posts

1 comment

How to make a searchable drop-down listing in PHP — Geek Steps June 5, 2020 - 12:22 PM

[…] Here is a Java Scanner Tutorial that you can check out from here […]

Reply

Leave a Comment