Scanner class 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. Like a real scanner, it reads data from a source that you specify (for example, a string, a file, the console). Next, it identifies the information and processes it appropriately. It is the easiest way to read input in a Java program, though not very efficient.
Once you’ve created a Scanner object, you can use the next methods to read data from the console. The method you use depends on the type of data you need to read. To read string data, for example, you use the next method. To read integer data, you use the nextInt method. To read double data, you use the the nextDouble method. And to read all of the data on a line, you use the nextLine method. When one of the methods of the Scanner class is run, the application waits for the user to enter data with the keyboard. To complete the entry, the user presses the Enter key.
// Java program to read data of various types using Scanner class public class ScannerExample { public static void main(String[] args) { // Declare the object and initialize with predefined standard input object Scanner sc = new Scanner(System.in); // Use '*' as delimiter instead of space. sc.useDelimiter("/*"); // String input String name = sc.nextLine(); // Read various type of data char gender = sc.next().charAt(0); int age = sc.nextInt(); long mobileNo = sc.nextLong(); double cgpa = sc.nextDouble(); // Close the scanner when not needed sc.close(); } }
To check if the scanner’s input is of the type we want, use hasNextXYZ() functions where XYZ is the type we are interested in. The function returns true if the scanner has a token of that type, otherwise false.
- hasNextInt(): This method checks whether the next chunk of input data is a number (returns true or false, as appropriate)
- hasNextLine(): This method checks whether the next chunk of data is a string.
- hasNextByte(), hasNextShort(), hasNextLong(), hasNextFloat(), hasNextDouble(): All these methods perform similar checks for the remaining data types.
Default token delimiter can be configured using useDelimiter(). You pass a string to this method. The string contains the characters you want to use as separators or delimiters.