dsa

Java Scanner Class

In this tutorial, we will learn about the Java Scanner Class, its constructors and its methods with the help of an example.

The Scanner class of the java.util package is used to read input data from different sources like input streams, users, files, etc.

Constructors of Scanner

Methods

MethodsDescription
nextInt()reads an int value from the user
nextFloat()reads a float value form the user
nextBoolean()reads a boolean value from the user
nextLine()reads a line of text from the user
next()reads a word from the user
nextByte()reads a byte value from the user
nextDouble()reads a double value from the user
nextShort()reads a short value from the user
nextLong()reads a long value from the user

Examples :


import java.util.Scanner;

class Codemistic 
{
    	public static void main(String[] args) 
	{

        	// creating a Scanner object
        	Scanner input = new Scanner(System.in);

        	System.out.println("Enter an integer: ");

        	// read an int value
        	int a = input.nextInt();
        	System.out.println("Using nextInt(): " + a);

		System.out.println("Enter a double: ");

        	// read an double value
        	double b = input.nextDouble();
        	System.out.println("Using nextDouble(): " + b);

		System.out.println("Enter a string: ");

        	// read an string value
        	String c = input.next();
        	System.out.println("Using next(): " + c);

		System.out.println("Enter a boolean value: ");

        	// read an boolean value
        	boolean d = input.nextBoolEAN();
        	System.out.println("Using nextBoolean(): " + d);
        	input.close();
    	}
}

Output :


Enter an integer: 
2
Using nextInt(): 2
Enter a double: 
55.00
Using nextDouble(): 55.0
Enter a string: 
codemistic
Using next(): codemistic
Enter a boolean value: 
true
Using nextBoolean(): true