Scanner Class in Java

The Scanner class lets you read an input source by tokens, somewhat analogous to the StreamTokenizer . The Scanner is more flexible in some ways—it lets you break tokens based on spaces or regular expressions—but less in others—you need to know the kind of token you are reading. In the Scanner you specify the input token types by calling methods like nextInt( ), nextDouble( ), and so on. Here is a simple example of scanning:

//From sampleScanner.java
String str = "12,Gautam,98.45";
            Scanner sc = new Scanner(str).useDelimiter(",");
            roll=sc.nextInt();
            name=sc.next();
            percentage=sc.nextFloat();

The Scanner is convenient because it can read not only from Strings but directly from stream sources, such as InputStreams, Files, and Channels:

    Scanner fileScanner = new Scanner( new File("spreadsheet.txt") );
    fileScanner.useDelimiter( “,”);
    // ...

Another thing that you can do with the Scanner is to look ahead with the "hasNext" methods to see if another item is coming:

    while( scanner.hasNextInt(  ) )
{
      int n = scanner.nextInt(  );
      ...
 }

The following table provides different scanner methods.

Scanner methods
Returned type
"has" method
"next" method
Comment
String
hasNext( )
next( )
The next complete token from this scanner
String
hasNext(Pattern)
next(Pattern)
The next string that matches the given regular expression (regex)
String
hasNext(String)
next(String)
The next token that matches the regex pattern constructed from the specified string
BigDecimal
hasNextBigDecimal( )
nextBigDecimal( )
The next token of the input as a BigDecimal
BigInteger
hasNextBigInteger(   )
nextBigInteger(   )
The next token of the input as a BigInteger
boolean
hasNextBoolean( )
nextBoolean( )
The next token of the input as a boolean
byte
hasNextByte( )
nextByte( )
The next token of the input as a byte
double
hasNextDouble( )
nextDouble( )
The next token of the input as a double
float
hasNextFloat( )
nextFloat( )
The next token of the input as a float
int
hasNextInt( )
nextInt( )
The next token of the input as an int
String
N/A
nextLine( )
Reads up to the end-of-line, including the line ending
long
hasNextLong( )
nextLong( )
The next token of the input as a long
short
hasNextShort( )
nextShort( )
The next token of the input as a short


Example:

import java.util.Scanner;
/**
 *
 * @author J a v a a t w e e t
 */

public class ScannerExample
{
  public static void main(String args[])
  {
      int roll;
      String name;
      float percentage;
      String str = "12,Gautam,98.45";
      Scanner sc = new Scanner(str).useDelimiter(",");
      roll=sc.nextInt();
      name=sc.next();
      percentage=sc.nextFloat();
      System.out.println(roll+"\n"+name+"\n"+percentage);
  }
}

Output:
12
Gautam
98.45