Scanner

java.util.Scanner – Scanner Java Example (with video)

In this example, we will show the range of functionality provided by the java.util.Scanner – Scanner Java class. We will also see how to use the Java Scanner class to read a Java input form the console. A simple text scanner which can parse primitive types and strings using regular expressions.

You can also check this tutorial in the following video:

Scanner Java Example – Video

1. Introduction

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

1
2
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

1
2
3
4
5
6
7
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

The following code shows you how you can use the Java Scanner class to read a Java input form the console. To start, you create a Scanner object passing System.in (which is the keyboard) as a parameter to the Constructor. Like the System.out object, the System.in object is created by Java automatically. Because of that, you can use this object with a Scanner object whenever you want to get a console input.

Once you’ve created a Scanner object, you can use the next methods to read data from the console. The method you use depends on the type of data you need to read. To read string data, for example, you use the next method. To read integer data, you use the nextInt method. To read double data, you use the the nextDouble method. And to read all of the data on a line, you use the nextLine method. When one of the methods of the Scanner class is run, the application waits for the user to enter data with the keyboard. To complete the entry, the user presses the Enter key.

Since the Scanner class is in the java.util package, you’ll want to include an import statement whenever you use this class.

2. Scanner Constructors

Here is a list of the Constructors in the Java scanner Class.

ConstructorDescription
1.Scanner(File source)Constructs a new Scanner that produces values scanned from the specified file.
2.Scanner(File source, String charsetName)Constructs a new Scanner that produces values scanned from the specified file.
3.Scanner(InputStream source)Constructs a new Scanner that produces values scanned from the specified Java input stream.
4.Scanner(InputStream source, String charsetName)Constructs a new Scanner that produces values scanned from the specified Java input stream.
5.Scanner(Path source)Constructs a new Scanner that produces values scanned from the specified file.
6.Scanner(Path source, String charsetName)Constructs a new Scanner that produces values scanned from the specified file.
7.Scanner(Readable source)Constructs a new Scanner that produces values scanned from the specified source.
8.Scanner(ReadableByteChannel source)Constructs a new Scanner that produces values scanned from the specified channel.
9.Scanner(ReadableByteChannel source, String charsetName)Constructs a new Scanner that produces values scanned from the specified channel.
10.Scanner(String source)Constructs a new Scanner that produces values scanned from the specified string.

3. Scanner Methods

Here is a list of the Methods in the Java scanner class.

Return TypeMethod NameDescription
1.voidclose()Closes this scanner.
2.Patterndelimiter()Returns the Pattern this Scanner is currently using to match delimiters.
3.StringfindInLine(String pattern)Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
4.StringfindInLine(Pattern pattern)Attempts to find the next occurrence of the specified pattern ignoring delimiters.
5.StringfindWithinHorizon(Pattern pattern, int horizon)Attempts to find the next occurrence of the specified pattern.
6.StringfindWithinHorizon(String pattern, int horizon)Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
7.booleanhasNext()Returns true if this scanner has another token in its input.
8.booleanhasNext(Pattern pattern)Returns true if the next complete token matches the specified pattern.
9.booleanhasNext(String pattern)Returns true if the next token matches the pattern constructed from the specified string.
10.booleanhasNextBigDecimal()Returns true if the next token in this scanner’s Java input can be interpreted as a BigDecimal using the nextBigDecimal() method.
11.booleanhasNextBigInteger()Returns true if the next token in this scanner’s input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method.
12.booleanhasNextBigInteger(int radix)Returns true if the next token in this scanner’s input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method.
13.booleanhasNextBoolean()Returns true if the next token in this scanner’s input can be interpreted as a boolean value using a case insensitive pattern created from the string “true|false”.
14.booleanhasNextByte()Returns true if the next token in this scanner’s input can be interpreted as a byte value in the default radix using the nextByte() method.
15.booleanhasNextByte(int radix)Returns true if the next token in this scanner’s input can be interpreted as a byte value in the specified radix using the nextByte() method.
16.booleanhasNextDouble()Returns true if the next token in this scanner’s input can be interpreted as a double value using the nextDouble() method.
17.booleanhasNextFloat()Returns true if the next token in this scanner’s input can be interpreted as a float value using the nextFloat() method.
18.booleanhasNextInt()Returns true if the next token in this scanner’s input can be interpreted as an int value in the default radix using the nextInt() method.
19.booleanhasNextInt(int radix)Returns true if the next token in this scanner’s input can be interpreted as an int value in the specified radix using the nextInt() method.
20.booleanhasNextLine()Returns true if there is another line in the input of this scanner.
21.booleanhasNextLong()Returns true if the next token in this scanner’s input can be interpreted as a long value in the default radix using the nextLong() method.
22.booleanhasNextLong(int radix)Returns true if the next token in this scanner’s input can be interpreted as a long value in the specified radix using the nextLong() method.
23.booleanhasNextShort()Returns true if the next token in this scanner’s input can be interpreted as a short value in the default radix using the nextShort() method.
24.booleanhasNextShort(int radix)Returns true if the next token in this scanner’s input can be interpreted as a short value in the specified radix using the nextShort() method.
25.IOExceptionioException()Returns the IOException last thrown by this Scanner’s underlying Readable.
26.Localelocale()Returns this scanner’s locale.
27.MatchResultmatch()Returns the match result of the last scanning operation performed by this scanner.
28.Stringnext()Finds and returns the next complete token from this scanner.
29.Stringnext(Pattern pattern)Returns the next token if it matches the specified pattern.
30.Stringnext(String pattern)Returns the next token if it matches the pattern constructed from the specified string.
31.BigDecimalnextBigDecimal()Scans the next token of the input as a BigDecimal.
32.BigIntegernextBigInteger()Scans the next token of the input as a BigInteger.
33.BigIntegernextBigInteger(int radix)Scans the next token of the input as a BigInteger.
34.booleannextBoolean()Scans the next token of the input into a boolean value and returns that value.
35.bytenextByte()Scans the next token of the input as a byte.
36.bytenextByte(int radix)Scans the next token of the input as a byte.
37.doublenextDouble()Scans the next token of the input as a float.
38.intnextInt()Scans the next token of the input as an int.
39.intnextInt(int radix)Scans the next token of the input as an int.
40.StringnextLine()Advances this scanner past the current line and returns the input that was skipped.
41.longnextLong()Scans the next token of the input as a long.
42.longnextLong(int radix)Scans the next token of the input as a long.
43.shortnextShort()Scans the next token of the input as a short.
44.shortnextShort(int radix)Scans the next token of the input as a short.
45.intradix()Returns this scanner’s default radix.
46.voidremove()The remove operation is not supported by this implementation of Iterator.
47.Scannerreset()Resets this scanner.
48.Scannerskip(Pattern pattern)Skips input that matches the specified pattern, ignoring delimiters.
49.Scannerskip(String pattern)Skips input that matches a pattern constructed from the specified string.
50.StringtoString()Returns the string representation of this Scanner.
51.ScanneruseDelimiter(Pattern pattern)Sets this scanner’s delimiting pattern to the specified pattern.
52.ScanneruseDelimiter(String pattern)Sets this scanner’s delimiting pattern to a pattern constructed from the specified String.
53.ScanneruseLocale(Locale locale)Sets this scanner’s locale to the specified locale.
54.ScanneruseRadix(int radix)Sets this scanner’s default radix to the specified radix.

4. Scanner Java Example

Let’s see a Scanner Java Example.

JavaUtilScannerExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.javacodegeeks.examples;
 
import java.util.Scanner;
 
public class JavaUtilScannerExample {
 
    public static void main(String[] args) {
        // Create a Scanner object
        try (Scanner scanner = new Scanner(System.in)) {
 
            // Read values from Console
 
            // A String value
            System.out.print("Enter Item Code: ");
            String itemCode = scanner.next();
 
            // A double value
            System.out.print("Enter Price: ");
            double price = scanner.nextDouble();
 
            // An int value
            System.out.print("Enter Quantity: ");
            int quantity = scanner.nextInt();
 
            // Display entered values
            double total = price * quantity;
            System.out.println();
            System.out.printf("%d %s @ %f = %f", quantity, itemCode, price, total);
 
            // Read three int values
            System.out.printf("Enter three integer values: ");
            int i1 = scanner.nextInt();
            int i2 = scanner.nextInt();
            int i3 = scanner.nextInt();
             
            // Calculate the average and display the result
            int avg = (i1 + i2 + i3) / 3;
             
            System.out.printf("Average: %d", avg);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }
}

Let’s explain the methods used in the above example.

  • public Scanner(InputStream source) – Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform’s default charset.
  • public String next() – Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
  • public double nextDouble() – Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
  • public int nextInt() – Scans the next token of the input as an int.

If we run the above code, we will get the following results:

1
2
3
4
5
6
7
8
Enter Item Code: 1
Enter Price: 10
Enter Quantity: 5
 
5 1 @ 10.000000 = 50.000000
 
Enter three integer values: 1 2 3
Average: 2

5. Common use of java.util.Scanner class

A common programming task involves parsing a string of text into words or “tokens” that are separated by some set of delimiter characters, such as spaces or commas.

ScannerTokenizingText.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.javacodegeeks.examples;
 
import java.util.Scanner;
 
public class ScannerTokenizingText {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        String text = "4231, Java Programming, 1000.00";
         
        Scanner scanner = new Scanner(text).useDelimiter("\\s*,\\s*");
        int checkNumber = scanner.nextInt();
        String description = scanner.next();
        float amount  = scanner.nextFloat();
         
        System.out.printf("/***** Tokenizing Text *****/\n\n");
         
        System.out.printf("String to tokenize: %s\n", text);
        System.out.printf("checkNumber: %d\n", checkNumber);
        System.out.printf("description: %s\n", description);
        System.out.printf("amount: %f", amount);
    }
}

Let’s explain the methods used in the above example.

  • public float nextFloat() – Scans the next token of the input as a float. This method will throw InputMismatchException if the next token cannot be translated into a valid float value as described below. If the translation is successful, the scanner advances past the input that matched.
  • public Scanner useDelimiter(String pattern) – Sets this scanner’s delimiting pattern to a pattern constructed from the specified String. An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as the invocation useDelimiter(Pattern.compile(pattern)). Invoking the reset() method will set the scanner’s delimiter to the default.

If we run the above code, we will get the following results:

1
2
3
4
5
6
/***** Tokenizing Text *****/
 
String to tokenize: 4231, Java Programming, 1000.00
checkNumber: 4231
description: Java Programming
amount: 1000.000000

6. Not so common use of java.util.Scanner class

The java.util.Scanner provides a single API for not only parsing indi‐ vidual primitive types from strings, but reading them from a stream of tokens.

The Scanner API is smarter and can use Locales to parse numbers in specific languages with more elaborate conventions. You can specify a Locale other than the default with the useLocale() method.

JavaNetURLMoreMethodsExample.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javacodegeeks.examples;
 
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
 
public class ScannerUncommonUses {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
 
        // Parsing primitive numbers
        boolean bl = new Scanner("false").nextBoolean();
        byte b = new Scanner("16").nextByte();
        int n = new Scanner("42").nextInt();
        long l = new Scanner("99999999999").nextLong();
        float f = new Scanner("4.2").nextFloat();
        double d = new Scanner("99.99999999").nextDouble();
 
        System.out.printf("/***** Parsing primitive numbers *****/\n\n");
        System.out.printf("boolean: %b\n", bl);
        System.out.printf("byte: %d\n", b);
        System.out.printf("int: %d\n", n);
        System.out.printf("long: %d\n", l);
        System.out.printf("float: %f\n", f);
        System.out.printf("double: %f\n\n", d);
 
        // Using Locale to parse numbers in specific languages
        try {
            double doubleLocale = new Scanner("1.234,56").useLocale(
                    Locale.ITALIAN).nextDouble();
 
            System.out.printf("/***** Using Locales to parse numbers in specific languages *****/\n\n");
            System.out.printf("double (Locale = Italy): %f", doubleLocale);
        } catch (InputMismatchException ime) {
            ime.printStackTrace(System.err);
        }
    }
}

Let’s explain the methods used in the above example.

If we run the above code, we will get the following results:

01
02
03
04
05
06
07
08
09
10
11
12
/***** Parsing primitive numbers *****/
 
boolean: false
byte: 16
int: 42
long: 99999999999
float: 4.200000
double: 100.000000
 
/***** Using Locales to parse numbers in specific languages *****/
 
double (Locale = Italy): 1234.560000

8. Download the source code

That was an example about the java.util.Scanner class. We also saw how to use this class to read a Java input form the console.

Download
You can download the source code of this example from here: java.util.Scanner – Scanner Java Example

Last updated on Apr. 27th, 2021

Armando Flores

Armando graduated from from Electronics Engineer in the The Public University Of Puebla (BUAP). He also has a Masters degree in Computer Sciences from CINVESTAV. He has been using the Java language for Web Development for over a decade. He has been involved in a large number of projects focused on "ad-hoc" Web Application based on Java EE and Spring Framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
narisip
7 years ago

what is this,,,,,, still not understanding everybody!!!!

Scanner
4 years ago

Java is a very necessary and useful programming language and it is used in various places. We can design and code scanner with the java with some advanced coding knowledge. Just we have to define the scanner class in the coding time.

Back to top button