Java Scanner : Basic Implementation of the Scanner Class

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

  • public String nextLine():Moves the scanner to the next line and returns the skipped input.
  • public String next(): Returns the token before delimiter
  • public byte nextByte(): Scans next token as byte value
  • public short nextShort(): Scans next token as short value
  • public int nextInt(): Scans next token as integer value
  • public long nextLong(): Scans next token as long value
  • public float nextFloat(): Scans next token as float value
  • public double nextDouble(): Scans next token as double value
  • void close: Scanner is closed

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);

  • int number = in.nextInt();
  • String string = in.nextLine();
  • float real = in.nextFloat();
  • String string2 = in.nextLine();

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.

  • boolean hasNextLine(): Returns true if scanner has input in next line else false
  • boolean hasNextInt(): Returns true if next token in scanner is integer
  • boolean hasNextFloat(): Returns true if next token in scanner is float.

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:

  • .hasNext();
  • .hasNextLine();

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.