java.util.Scanner
Description
The Scanner class has a rich set of API which generally used to break down the input to Scanner constructor into tokens. It can parse the tokens into primitive data types using java regular expressions. The input is broke down into tokens using the delimiter defined on the Scanner class using the radix method or can be define as well as method argument on some of the methods available on this scanner class.
Scanner Class Declaration
public final class Scanner
extends Object
implements Iterator, Closeable
Scanner Class Constructors
Scanner used to Read File
Reading a file is very easy using the Scanner class. We just have to declare it using the Scanner constructor like for example:
Scanner scan = new Scanner(new File("C:/test.txt"));
If we want to have a locale specific we just have to declare it using one of the Scanner method
scan.useLocale(Locale.ENGLISH);
The trick in iterating through the Scanner token is to use those methods which starts with has like hasNext, hasNextInt, etc. For the purpose of discussion, let’s settle first in reading the file line by line.
while(scan.hasNextLine()){ System.out.println(scan.nextLine()); } scan.close();
From the java code snippet above we have used the scan.hasNextLine() flag as a means to check if there are token which in this example available on the scanner input. The nextLine() method returns the current token and advances to the next token. The combination of the hasNextLine() and the nextLine() combination is widely used to get all the tokens on the scanner input. Afterwards we call the close() method to close the Scanner object and thereby avoid memory leak.
Read string from Console Input using Scanner Class Example
The Scanner class accepts also an InputStream on one of its constructor. Thus in reading console input can be done using:
Scanner scan = new Scanner(System.in);
After putting the console input to our scanner object, we now have the access to a readable and convertible stream which means we can manipulate or either break the input into tokens. Using the rich set of Scanner API we can read the tokens depending on the delimiter which we want to use into specific data type.
Scanner Tips
I have recently discovered one problem in using Scanner. Let’s say for example, we are asking the user to input employee id and employee name from the user console. After which we will read the input from the console using Scanner. The employee id would be read using nextInt() and the employee name would be read as nextLine(). It’s pretty straightforward isn’t it? Well this won’t work. Try below example:
package com.javatutorialhq.java.examples; import java.util.Scanner; /* * Java Example to get employee id * and employee name from the console * and get it using Scanner */ public class Demo { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("Enter employee id:"); int empId = scan.nextInt(); System.out.print("Enter employee name:"); String empName = scan.nextLine(); scan.close(); } }
Above example would not work because the nextInt method does not read the last newline character of your input, and thus that newline is consumed in the next call to nextLine. To resolve this just use next instead of nextline but if you insist of using nextLine add another scan.nextLine() after nextInt. Take a look below snippet
Scanner scan = new Scanner(System.in); System.out.print("Enter employee id:"); int empId = scan.nextInt(); scan.nextLine(); System.out.print("Enter employee name:"); String empName = scan.nextLine(); scan.close();
Java Scanner Method Examples
The following are the list of Scanner methods which we can use to work out in complicated parsing of input.
return | Method | Description |
---|---|---|
void | close() | Closes the scanner object. |
Pattern | delimiter() | Returns the Pattern the Scanner object is currently using to match delimiters. |
String | findInLine(Pattern pattern) | This method returns a String object that satisfies the Pattern object specified as method argument. |
String | findInLine(String pattern) | Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters. |
String | findWithinHorizon(Pattern pattern, int horizon) | Attempts to find the next occurrence of the specified pattern. |
String | findWithinHorizon(String pattern, int horizon) | This method simply attempts to find the next occurrence of a pattern input ignoring delimiter |
boolean | hasNext() | Returns true if this scanner has another token in its input. |
boolean | hasNext(Pattern pattern) | Returns true if the next complete token matches the specified pattern. |
boolean | hasNext(String pattern) | Returns true if the next token matches the pattern constructed from the specified string. |
boolean | hasNextBigDecimal() | Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method. |
boolean | hasNextBigInteger() | Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method. |
boolean | hasNextBigInteger(int radix) | Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method. |
boolean | hasNextBoolean() | This method checks if the Scanner object has boolean data type on its buffer. |
boolean | hasNextByte() | This method returns true if the next byte on the scanner buffer can be translated to byte data type otherwise false. |
boolean | hasNextByte(int radix) | Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte() method. |
boolean | hasNextDouble() | Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. |
boolean | hasNextFloat() | Returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. |
boolean | hasNextInt() | Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. |
boolean | hasNextInt(int radix) | This method returns boolean, true if the token can be interpreted as int data type with respect to the radix used by the scanner object otherwise false. |
boolean | hasNextLine() | This method returns a boolean data type which corresponds to the existence of new line on the String tokens which the Scanner object holds. |
boolean | hasNextLong() | Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method. |
boolean | hasNextLong(int radix) | Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong() method. |
boolean | hasNextShort() | Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method. |
boolean | hasNextShort(int radix) | This method returns boolean, true if the token can be interpreted as short data type with respect to the radix used by the scanner object otherwise false. |
IOException | ioException() | Returns the IOException last thrown by this Scanner's underlying Readable. |
Locale | locale() | This method returns a Locale which the Scanner class is using. |
MatchResult | match() | This method returns a MatchResult object which corresponds to the result of the last operation by the scanner object. |
String | next() | Finds and returns the next complete token from this scanner. |
String | next(Pattern pattern) | Returns the next token if it matches the specified pattern. |
String | next(String pattern) | Returns the next token if it matches the pattern constructed from the specified string. |
BigDecimal | nextBigDecimal() | Scans the next token of the input as a BigDecimal. |
BigInteger | nextBigInteger() | Scans the next token of the input as a BigInteger. |
BigInteger | nextBigInteger(int radix) | Scans the next token of the input as a BigInteger. |
boolean | nextBoolean() | Scans the next token of the input into a boolean value and returns that value. |
byte | nextByte() | Scans the next token of the input as a byte. |
byte | nextByte(int radix) | Scans the next token of the input as a byte. |
double | nextDouble() | Scans the next token of the input as a double. |
float | nextFloat() | Scans the next token of the input as a float. |
int | nextInt() | Scans the next token of the input as an int. |
int | nextInt(int radix) | Scans the next token of the input as an int. |
String | nextLine() | Advances this scanner past the current line and returns the input that was skipped. |
long | nextLong() | Scans the next token of the input as a long. |
long | nextLong(int radix) | Scans the next token of the input as a long. |
short | nextShort() | Scans the next token of the input as a short. |
short | nextShort(int radix) | Scans the next token of the input as a short. |
int | radix() | Returns this scanner's default radix. |
void | remove() | The remove operation is not supported by this implementation of Iterator. |
Scanner | reset() | Resets this scanner. |
Scanner | skip(Pattern pattern) | Skips input that matches the specified pattern, ignoring delimiters. |
Scanner | skip(String pattern) | Skips input that matches a pattern constructed from the specified string. |
String | toString() | Returns the string representation of this Scanner. |
Scanner | useDelimiter(Pattern pattern) | Sets this scanner's delimiting pattern to the specified pattern. |
Scanner | useDelimiter(String pattern) | Sets this scanner's delimiting pattern to a pattern constructed from the specified String. |
Scanner | useLocale(Locale locale) | Sets this scanner's locale to the specified locale. |
Scanner | useRadix(int radix) | Sets this scanner's default radix to the specified radix. |
Java Scanner FAQ’s
The following Questions are gathered around the web and from the mails of our beloved which I have compiled and answer them one by one. This is to further discuss in depth what is scanner in java.