Java Scanner – Comprehensive Guide with Examples

October 06, 2021
Xblog JavaScanner



Overview

One of the most basic yet very important functionalities of any programming language is to successfully take input from the user and displaying the correct output. A programming language would be of no use without these two functions. Java, being a programming language, also offers these functionalities that allow a Java program to take input and display the output to the user. The output on the screen is printed using System.out.print() and System.out.println() functions in Java. These functions are part of the Java Scanner class.

In this article, you will discuss the input functionality of the Java language using the Java’s Scanner class. We will also learn about the various methods offered by the scanner class in Java with the aid of examples.

Java Scanner Class

Scanner Java class is part of the Java.util package. It is used to get input from the user during runtime. The input is supposed to be of primitive data types, like int, float, double, string, etc.

There are different functions in Java’s Scanner Class used to take input directly from the user or read from a file. For instance, nextint() is used to take integer type input, and nextfloat() is for float type input. Similarly, nextLine() and next() are used for string type and char type inputs. Although these functions are the easiest methods to read the input, these are often not the most efficient ones.

How To Import Java Scanner Class?

Like any other class, The package of the Scanner class java.util.Scanner is needed to be imported first to use the Java’s Scanner class.  Either of the following statements can be used to import the Java’s Scanner class and its functionality in your program.

import java.util.Scanner;

OR

import java.util.*

Creating a Scanner Class Object

After importing the package, the following lines of codes can be used to create an object of the Scanner class. It can read input from a File, InputStream, and a String respectively.

1. //read input from a file (“myFile”)
2. Scanner sc01 = new Scanner(File “myFile”);
3. //read input from the input stream
4. Scanner sc02 = new Scanner(inputStream input);
5. //read input as a String
6. Scanner sc03 = new Scanner(String str);

Java Scanner Methods

After creating a Scanner object, now we can use a method to take input of a data type. As discussed before, the Scanner class provides a lot of methods that can be used to read inputs of different data types.

The following table shows some commonly used Scanner functions to read input from the user along with their respective data types:

Method Data Type
nextInt() Int
nextFloat() Float
nextBoolean() Boolean
nextLine() String
next() String
nextByte() Byte
nextDouble() Double

The following series of codes demonstrate the use of some of the Java’s Scanner methods along with their outputs:

· Java Scanner nextInt() method

1. import java.util.Scanner;
2. class Main {
3.   public static void main(String[] args) {
4.    // creating a Java's Scanner object
5.    Scanner inputInteger = new Scanner(System.in);
6.    System.out.println("Please enter an integer: ");
7.    // Takes an integer value
8.    int input01 = inputInteger.nextInt();
9.    System.out.println("Output using nextInt(): " + input01);
10.    inputInteger.close();
11.  }
12.}

This is the output of this code,

Please enter an integer:

45

Output using nextInt(): 45

· Java Scanner nextDouble() method

1. import java.util.Scanner;
2. class Main {
3.  public static void main(String[] args) {
4.    // creating a Scanner object
5.    Scanner inputDouble = new Scanner(System.in);
6.    System.out.print("Enter a Double value: ");
7.    // takes the double value as input
8.    double data = inputDouble.nextDouble();
9.    System.out.println("Output using nextDouble(): " + data);
10.    input.close();
11.  }
12. }

 Following is the Output,

Enter a Double value: 3.142

Output using nextDouble(): 3.142

· Java Scanner next() method

1. import java.util.Scanner;
2. class Main {
3.  public static void main(String[] args) {
4.    // creating a scanner object
5.    Scanner inputWords = new Scanner(System.in);
6.    System.out.print("Enter names of three animals: ");
7.    // reads a single word
8.    String word = inputWords.next();
9.    System.out.println("Output using next(): " + word);
10.    input.close();
11.   }
12.  }

 Following will be the Output,

Enter names of three animals: cat sheep goat

Output Using next(): cat

Here, I have provided three words. However, the next() method only reads the single word. This is because the next() method reads input up to the first whitespace character. As it encounters whitespace, it returns the string (without the whitespace).

· Java Scanner nextLine() method

1. import java.util.Scanner;
2. class Main {
3.   public static void main(String[] args) {
4.     // creating a scanner object
5.     Scanner inputLine = new Scanner(System.in);
6.    System.out.print("Please enter your full name: ");
7.    // takes the entire line as input
8.    String name = inputLine.nextLine();
9.    System.out.println("Output using nextLine() method: " + name);
10.    inputLine.close();
11.   }
12.  }

 The output will be:

Please enter your full name: Shaharyar Lalani

Output using nextLine() method: Shaharyar Lalani

The nextLine() method is used to read a string from the user. Unlike the next() method, the nextLine() method reads the entire line of input with white spaces. The method is only terminated when a next line character, n is encountered.

Java Scanners Class Constructor

Like any other class, the Java’s Scanner class contains various overloaded constructors that offer various input methods like System.in, file input, path, etc. The input can be a file object as well, which allows a Java program to take input from a file.

Constructor Description
Scanner(File FileSourceName) It creates a new Scanner that scans from the FileSourceName.
Scanner(inputStream inputStreamSource)  

It creates a new scanner that scans from the inputStreamSource passed as a parameter.

Scanner(Readable ReadableSource)  

It creates a new scanner that scans from the ReadableSource passed as a parameter.

Scanner(String StringSource)  

It creates a new scanner that scans from the StringSource passed as a parameter.

 

Scanner(ReadableByteChannel ChannelSource)

It creates a new scanner that scans from the ChannelSource.
Scanner(Path PathSource)  

It creates a new scanner that scans from the PathSource mentioned.

All the above constructors can be overridden by adding another parameter, charsetName of string data type.

Java Scanners Class Delimiters

Scanner Java class can also be used to split the input. The default delimiter is the whitespace that is why we get the spaces in between the tokens, but users can also specify the delimiter of their choice by a simple change in Code.

Following is the Java code snippet for Scanner delimiter usage:

1. import java.util.*;
2. public class DelimiterExample {
3. public static void main(String[] args) {
4. Scanner sc = new Scanner(“44, 98, 32, 37”);
5. sc.useDelimiter(“\s*, \s*);
6. while(sc.hasNext()) {
7.   System.out.println(sc.nextInt());
8.       }
9.     }
10.  }

 Output:

44

98

32

37

In this example, ‘,’ (comma) is accompanied by any number of spaces before and after it has been set as a delimiter so when a comma is found in the input, the data will be separated with a new line.

It can be very helpful if your existing data is present in a certain format and you want to change it when read in from the file.

Drawbacks Of Java Scanner Class

Although the Scanner Java class seems very useful when taking the input at run time, there are some drawbacks of using the Scanner class in Java. A java developer must keep the following points in account when using the Scanner Java class.

When any next<xxx>() method is utilized after the nextLine() method, the input entered during the execution of nextLine() method is ignored. This makes it not a very efficient way to take input in Java as it can ultimately result in unexpected output and if a Java developer is not fully aware of this scenario, it might get very frustrating for you to find the error.

See Also: Inheritance In Java: Inheritance Types With Example

This happens because the values entered with the nextLine() method get ignored by the console, and that step is ignored altogether. The Scanner class in Java is also relatively slower as it takes significant time when the input data gets parsed in the Scanner class.

Conclusion

This was all about the Scanner class in Java. We have covered all the details about the Java’s Scanner class, including how to import the Scanner class, how to create an object, and how to use the functions with various examples. Java Scanner constructor and Java delimiters are also covered. Along with that, we discussed the certain drawbacks of using the Scanner Java class that you should be aware of. It is a very easy-to-use method to take input if effectively implemented and the user is fully aware of the problems that may arise.



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US