Java Scanner Class With Examples

In this article I shall discuss about the Java Scanner Class. I shall discuss about the concept with some examples. When you get to know the basics of programming, with time comes the desire that a developer has to work with novice programs in text mode (console). With this principle, many begin to use the scanner class , precisely because it has the purpose of facilitating the input of data in the console. This class was introduced in Java 5. Earleri to Java 5 it was difficult to create programs that received variable values ​​in Console mode.

Java Scanner Concept

The meaning of the Scanner class for many in the beginning is a bit complicated to understand, but with time the programmer just gets used to its definition. A simple text scanner can parse primitive types and Strings using regular expressions.

The class Scanner aims to separate the entry of text into blocks, generating the known tokens, which are sequences of characters separated by delimiters by default corresponding to blanks, tabs, and newline.

With this class you can convert text to primitives, and these texts can be considered as objects of type String, InputStream and files.

Java Scanner In Practice

Importing the Scanner class
First of all, you must know are some functions and features of this class. When using with the Scanner class, the compiler will ask you to do the following imports:

import java.util.Scanner;

Declarations Scanner
As described in the introduction, this class helps in reading the data. The example below shows how to use the Scanner object. First it is necessary to create an object of type Scanner and then an argument of object System.in to the Scanner constructor, as follows:

package net.javabeat;

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 Patil";
		// Read from a String
		Scanner sc2 = new Scanner(textString);
	}
}

Count tokens in the string

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 the input to read data.

package net.javabeat;

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 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 invoked based on the input data type. i.e, for each primitive there is a method call to return the value of input data type.

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

As the class Scanner reads data as command line arguments, it is always a good practice to use try/catch. This helps avoid the exceptions caused due to wrong data type entry. For example in the below image you can see that a wrong data type entry to the method which was expecting a data of type Double, causes an exception.

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 see a full fledged example of what can be done with the Scanner class. The classes IndividualScannerTest and Person make use of object-oriented programming (OOP). The aim is to show object manipulation. Methods setters (setAttributeName) keeps the value entered which are then used to generate the output of each object created in the list.

package net.javabeat;

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";
	}
}

The class IndividualScannerTest shows that several Person objects can be stored in a list and later printed.

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

package net.javabeat;

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<Person> personList = new ArrayList<Person>();
		int option = 0;

		do {
			System.out.println("# # Choose one of the 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 here:");
			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 preceeding example we read data from command line. if data is huge its better idea to store it in a file and then read the data from this file. Let us see 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.
	}
}

Conclusion

In this article we saw some basic concepts of Scanner class in Java. A scanner class is basically used to read data from command line input or from a file system. If you are interested in receiving the future articles, please subscribe here. follow us on @twitter and @facebook.

Comments

comments

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better