Java-Next and HasNext Methods

Next and HasNext Methods

Once you have created a Scanner, it is a simple matter to use it to read formatted input. In general, a Scanner reads tokens from the underlying source that you specified when the Scanner was created. A token is a portion of input that is delineated by a set of delimiters, which is whitespace by default.

Scanner defines two sets of methods that enable you to read input. The first are the following methods determine if the specified type of input is available. For example, calling hasNextInt( ) returns true only if the next token to be read is an integer.

Method Description
boolean hasNext( ) Returns true if another token of any type is available to be read. Returns false otherwise.
boolean hasNext(String str ) Returns true if a token that matches the str passed in str is available to be read. Returns false otherwise.
boolean hasNextBoolean( ) Returns true if a boolean value is available to be read. Returns false otherwise.
boolean hasNextInt( ) Returns true if an int value is available to be read. Returns false otherwise.
boolean hasNextShort( ) Returns true if a short value is available to be read. Returns false otherwise.

If the desired data is available, then you read it by calling one of following methods. For example, to read the next integer, call nextInt( ).

Method Description
String next( ) Returns the next token of any type from the input source.
String next(String str) Returns the next token that matches the str passed in str from the input source.
boolean nextBoolean( ) Returns the next token as a boolean value.
int nextInt( ) Returns the next token as an int value.
short nextShort( ) Returns the next token as a short value.

The following program shows how to read a list of integers from the string. The while loop stops as soon as the next token is not an integer. Thus, the loop stops reading integers as soon as a non-integer is encountered in the input stream.

Program

Program Source

import java.util.Scanner;

public class Javaapp {
 
    public static void main(String[] args) {
        
        String str = "10 20 30  40    50    60 70";
        int i = 0;
        
        Scanner instr = new Scanner(str);
        
        while(instr.hasNextInt())
        {
            i = instr.nextInt();
            System.out.println("Integer i = "+i);
        }
        instr.close();
    }
}

Leave a Comment