Scanner

Scanner is a class in java.util package used for obtaining the input of the primitive types such as int, double etc. and strings. this is the easiest way to read input in a Java program, however, if you want an input method for scenarios where time is a constraint like in competitive programming.

  • To create an object of a scanner class, we usually pass the predefined object System.in, which represents the standard input stream. If we want to read the input from a file, then we can pass the object of the class file.
  • To read numerical values of a certain data type XYZ then, the function to use is nextXYZ(). For example, read a value of type short, we can use nextShort()
  • To read strings, we use the nextLine().
  • To read a single character, we use the next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.
Example:

// Java program read data of various types using Scanner class. 

import java.util.Scanner;
public class ScannerExample {
	public static void main(String[] args) {
		// Declare object and initialize  
		// predefined standard input object 
		Scanner sc = new Scanner(System. in );

		// String type input 
		String name = sc.nextLine();

		// Character type input 
		char gender = sc.next().charAt(0);

		// Numerical type data input 
		// byte, short and float can be read 
		// using similar-named functions. 
		int age = sc.nextInt();
		long mobileNo = sc.nextLong();
		double address = sc.nextDouble();

		// Print values to check if input was correctly obtained. 
		System.out.println("Name: " + name);
		System.out.println("Gender: " + gender);
		System.out.println("Age: " + age);
		System.out.println("Mobile Number: " + mobileNo);
		System.out.println("CGPA: " + cgpa);
	}
}


Input :
Raj
M
35
9876543210
9.4


Output :
	
Name: Raj
Gender: M
Age: 35
Mobile Number: 9876543210
CGPA:9.4

Importing the Scanner class :

You should know that there are some functions and features of this class. When used with the scanner class, the compiler will ask you to import the following: import java.util.Scanner;

Declarations Scanner :

As mentioned in the introduction, this class helps in reading data. The example below shows how to use the scanner object. First of all, it is necessary to create an object of scanner type and then make the scanner constructor the argument of System.in:


package net.javascanner;

import java.util.Scanner;

public class TestScannerDeclaration {
	public static void main(String[] args) {
		// Read from the command line
		Scanner sc1 = new Scanner(System. in );
		String textString = "Manisha lamba";
		// Read from a String
		Scanner sc2 = new Scanner(textString);
	}
}

Now that you scanner class is created, let’s see how to read the data. The xample below shows we need to iterate through each token in input to read data.


package net.javascanner;

import java.util.Scanner;

public class CountTokens {
	public static void main(String[] args) {
		int i = 0;
		Scanner sc = new Scanner(System. in );
		System.out.print("Enter some text:");
		while (sc.hasNext()) {
			i++;
			System.out.println("Token:" + sc.next());
		}
		sc.close(); // End of the program
	}
}

The object System.in takes the input that you type from your keyboard.

Methods of class Scanner

Below are some of the main methods that can be called based on the input data type. That is, a method call is to return the value of the input data type for each primitive


Scanner sc = new  Scanner(System.in);
float numF = sc.nextFloat();
int num1 = sc.nextInt();
byte byte1 = sc.nextByte();
long lg1 = sc.nextLong();
boolean b1 = sc.nextBoolean();
double num2 = sc.nextDouble();
String name = sc.nextLine();

Demonstration of exception InputMismatchException :

Since the class scanner reads the data as a command line argument, it is always a good practice to try / catch. This helps in avoiding the exceptions due to incorrect data type insertion.

For example, in the below you can see that a wrong data type entry to the method which was expecting a data of type Double, causes an exception.

Scanner Class Methods :

Below is a list of some of the main methods of the Scanner class.

  • close() : Closes the current scanner.
  • findInLine() : Attempts to find the next occurrence of the specified pattern ignoring delimiters
  • hasNext() : Returns true if this scanner has another token in its input
  • hasNextXyz() : Returns true if the next token in this scanner’s input can be interpreted as a Xyz in the default radix using the nextXyz() method.Here Xyz can be any of these types:BigDecimal,BigInteger, Boolean, Byte, Short, Int, Long, Float, or Double.
  • match() : Returns the match result of the last scanning operation performed by this scanner.
  • next() : Finds and returns the next complete token from this scanner.
  • nextXyz() : Scans the next token of the input as a Xyz where Xyz can be any of these tyeps: boolean, byte, short, int, long, float or double.
  • nextLine() : Advances this scanner past the current line and returns the input that was skipped
  • radix() : Returns the current index of the Scanner object
  • remove() : This operation is not supported by the implementation of an Iterator
  • skip() : Skip to the next search for a specified pattern ignoring delimiters
  • string() : Returns a string representation of the object is a Scanner


Example:
Let’s full fledged example of what can be done with the Scanner class. The classes Individual Scanner Test and Person make use of the object-oriented programming (OOP).

The aim is to show object manipulation. Methods setters (setAttributeName) keeps the value entered that are then used to generate the output of each object created in the list.


package net.javascanner;

public class Person {
	private Integer code;
	private String name;
	private String address;
	private Integer age;

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "code:" + code + "" + "\n" + "Name:" + name + "" + "\n" + "Address:" + address + "" + "\n" + "Age:" + age + "\n";
	}
}

Class Individual Scanner shows that many people objects can be stored in a list and can be printed later.

Take a test, insert two or more entries and then choose option 2. All Person objects stored in the list will be printed.


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class IndividualScannerTest {
	public static void main(String[] args) {
		peopleData();
	}
	public static void peopleData() {
		Scanner sc = new Scanner(System. in );
		Person person;
		List & ltPerson > personList = new ArrayList & ltPerson > ();
		int option = 0;
		do {
			System.out.println("# # Choose only one options below # #");
			System.out.println("Option 1 - Enroll people");
			System.out.println("Option 2 - Print people registered");
			System.out.println("Option 0 - Exit program");
			System.out.println("_______________________");

			System.out.print("Enter your choice :");
			option = Integer.parseInt(sc.nextLine());

			if (option == 1) {
				// Create a new object
				person = new Person();

				System.out.print("Enter code:");
				person.setCode(Integer.parseInt(sc.nextLine()));

				System.out.print("Enter the name:");
				person.setName(sc.nextLine());

				System.out.print("Enter the address:");
				person.setAddress(sc.nextLine());

				System.out.print("Enter the age:");
				person.setAge(Integer.parseInt(sc.nextLine()));

				System.out.println();

				// Holds the person object in a list.
				personList.add(person);
			}
			else if (option == 2) {
				if (personList.isEmpty()) {
					System.out.println("There are people registered, press any key to continue");
					sc.nextLine();
				}
				else {
					System.out.println(personList.toString());

					System.out.println("Press one key to continue.");
					sc.nextLine();
				}
			}
		} while ( option != 0 );

		sc.close();
	}
}

Reading data from a file

In the preceding example, we read data from the command line. Sometimes we might use the scanner class to read the data from ten files..

Let us an example of how to read data from a file using Scanner class.


package net.javabeat;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
	public static void SpeakIt(String fileName) {
		try {
			File file = new File(fileName);
			Scanner sc = new Scanner(file);
			while (sc.hasNext()) {
				System.out.print(sc.nextLine());
			}

			sc.close();
		} catch(FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		SpeakIt("samplefile.txt"); // change the path of the desired file.
	}
}

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : We have closed registration for training

Please do email to chercher.tech@gmail.com for any queries

If you already registered then please do check your email for the Webex link
 
Join My Facebook Group