Java Scanner Examples

The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. With the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.

How does a Scanner work?

Basically, a Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace (blanks, tabs, and line terminators). The parsed tokens can be converted into primitive types and Strings using various next methods. 
Here’s the simplest example of using a Scanner to read String from the user:
System.out.println("Enter string input: ");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();

Java Scanner Examples - Read a user input

Here is the complete Java program to read primitive types and strings from User's input:
package net.javaguides.examples;

import java.util.Scanner;

/**
 * Scanner class examples
 * @author Ramesh Fadatare
 *
 */
public class ScannerExamples {
    public static void main(String[] args) {

        // Create Scanner object
        Scanner scanner = new Scanner(System.in);

        // read user input as string
        System.out.println("Enter string input: ");
        scanner.nextLine();

        // read user input as integer
        System.out.println("Enter integer input");
        scanner.nextInt();

        // read user input as long
        System.out.println("Enter long input");
        scanner.nextLong();

        // read user input as float
        System.out.println("Enter float input");
        scanner.nextFloat();

        // read user input as byte
        System.out.println("Enter byte input");
        scanner.nextByte();

        // read user input as short
        System.out.println("Enter short input");
        scanner.nextShort();

        // read user input as boolean
        System.out.println("Enter boolean input");
        scanner.nextBoolean();

        // read user input as BigDecimal
        System.out.println("Enter BigDecimal input");
        scanner.nextBigDecimal();

        // read user input as BigInteger
        System.out.println("Enter BigInteger input");
        scanner.nextBigInteger();

        scanner.close();
    }
}
Output:
Enter string input: 
Ramesh
Enter integer input
100
Enter long input
120
Enter float input
12
Enter byte input
12
Enter short input
1
Enter boolean input
true
Enter BigDecimal input
120.01
Enter BigInteger input
12346

References


Comments