Udemy logo

java scannerThe Scanner class in Java is used for taking input from the user. The Scanner class can take input of all the data types. Scanner splits the input after every whitespace. This class is present in java.util package.

Class Declaration:

public final class Scanner extends Object implements Iterator<String>

The Scanner class uses various methods to read different data types of input from the keyboard.

Learn the basics of Java at Udemy.com

Learn more about Java programming in detail at Udemy.com

The Scanner searches for tokens in input. Basically, a token is a series of numeric or alphanumeric characters that ends with a whitespace. A whitespace can be  tab character, carriage return, end of file or a blank space. If a series of numbers are given as input by the user with spaces in between each number, then the Scanner class would take every number as a separate token. We can then say that whitespace characters act as separators.

Constructor of Scanner Class:

There are two constructors of the Scanner class that are used. One is the InputStream object and other takes a FileReader object.

Syntax:

Scanner in = new Scanner(System.in);  //InputStream
Scanner inFile = new Scanner(new FileReader(“File_Object”));

If file is not found “FileNotFoundException” is thrown.

Example Syntax for various Datatypes:

Scanner in = new Scanner(System.in);

Want to learn Java from scratch? Take a tutorial at Udemy.com

Example Program

import java.util.Scanner;
import java.io.*;
class InputScanner
{
public static void main(String[] args)
{
// Declarations of variables
Scanner scant = new Scanner(System.in);
int integer_type;
long long_type
float real_type;
double double_type;
String string2;
// Prompts the User
System.out.println("Enter three numbers integer,long and float ");
System.out.println("Enter number, another floating-point number, " + "and a string.");
System.out.println("Separate each input with  blank or return.");
// Read in values
integer_type = scant.nextInt();
long_type = scant.nextLong();//taking long type input
real_type = scant.nextFloat();//taking float type input
double_type = scant.nextDouble();//taking double type input
System.out.println("enter one more value.");
string2 = scant.next(); // string input
System.out.println("Here is the output Created: ");
System.out.println(integer_type + " " + long_type + " " + real_type + " " + double_type + " " + string2);
}
}

Output

Enter three numbers integer,long and float

Enter number, another floating-point number and a string.

Separate each with a blank or return.

33

100000

1.2343

343.645645

enter one more value.

Input

Here is the output Created:

33 100000 1.2343 343.645645 Input

The Scanner method throws “InputMismatchException” exception if the next value does not match the data type expected. This situation is avoided using boolean methods.

Example

Scanner scant = new Scanner(System.in);
System.out.println(scant.nextInt());
if (scant.hasNextInt()) // Checks if next line has integer input
System.out.println(scant.nextInt());

Example Program

import java.io.*;
import java.util.Scanner;
public class MixedInput
{
public static void main(String[] args)throws Exception
{
double number;
Scanner scant = new Scanner(System.in);
System.out.println("Enter your gross income: ");
if (scant.hasNextInt())
{
number = (double)scant.nextInt();
System.out.println("You entered " + number);
}
else if (scant.hasNextFloat())
{
number = (double)scant.nextFloat();
System.out.println("You entered " + number);
}
else if (scant.hasNextDouble())
{
number = scant.nextDouble();
System.out.println("You entered " + number);
}
else {
System.out.println("Not a real value or integer value.");
}
}

Output

Enter your gross income:

45000

You entered 45000.0

Enter your gross income:

45000.0

You entered 45000.0

Enter your gross income:

45E10

You entered 45000.0

Enter your gross income:

Forty Five Hundred

Not a real value or integer value.

Only when the next input will be given the scanner will insert inside the if statement section and store the value

Example 2

import java.util.*;
public class ScannerDemo {
public static void main(String[] args)
{
String s = "Hello World! 4 + 4.0 = 8 ";
// create a new scanner with the specified String Object
Scanner scant = new Scanner(s); // String passed into Scanner object
// find the next token and print it
System.out.println("" + scant.next());//Every token of String given is read and is Printed on screen
// find the next token and print it
System.out.println("" + scant.next());
// close the scanner
scant.close();
}
}

Output

Hello

World!

Reading input from File using Scanner class.

The boolean method is generally used when reading input from the file. This method loops to read complete data in the whole file.

Syntax:

Scanner inFile = new Scanner (new FileReader(File_obj)); // Reading from a file

The two Scanner methods to read input from a file are:

They return true if file has another token i.e. line in the file.

For Example:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerRead
{
public static void main(String[] args)
{
// Create an object of File
File fileinput = new File("data.txt”);//file to be read
try {
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scant = new Scanner(fileinput);//Object of class Scanner
while (scant.hasNextLine()) //Check next token
{
String line = scant.nextLine();
System.out.println(line);//Print line by line
}
} catch (FileNotFoundException e) //File not found exception
{
e.printStackTrace();
}
}
}

The file object is created inside, which the address of the file and name is given. This file object is then passed to the Scanner class  object  and then Scanner methods are used to read through the file.

Page Last Updated: May 2014

Top courses in Java

Java Interview Help
Bharath Thippireddy
4.6 (1,180)
Java Programming for Complete Beginners
in28Minutes Official
4.5 (38,781)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,369)
Bestseller
Java for Absolute Beginners
Nick H
4.6 (7,429)
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.5 (3,634)
Bestseller
Learn Selenium with Java, Cucumber + Live Project
Pavan Kumar
4.6 (4,233)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 2
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.3 (993)
Java Tutorial for Beginners
Navin Reddy
4.5 (520)
Java Streams API Developer Guide
Nelson Jamal
4.6 (3,403)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo