Somenath Sinha Somenath Sinha - 6 months ago 8
Java Question

How does this program accept data without knowing its datatype?

This is a program that checks what kind of input is available via the System.in Input Stream and decides what datatype of a variable to store it in. The code of the program is :

import java.util.Scanner;
public class hasNextNumberDemo
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your Data :");
if(in.hasNextInt())
System.out.println("You have entered an Integer as : " + in.nextInt());
else if(in.hasNextFloat())
System.out.println("You have entered an Float Value as : " + in.nextFloat());
else if(in.hasNextDouble())
System.out.println("You have entered an Double Value as : " + in.nextDouble());
else
System.out.println("Token not an Integer or a real value.");
}
}


Here, we clearly see that the data can be accepted via multiple points :
in.nextInt()
or
in.nextFloat()
or even
in.nextDouble()
, but all are preceded by a statement to check the datatype of the input (which is yet to be entered [via
hasNextInt()
or
hasNextFloat()
or
hasNextDouble()
]).

My question is how does the program decide what datatype the next token is BEFORE accepting the data?

Further, if
hasNextInt()
or
hasNextFloat()
or
hasNextDouble()
triggers the input of data, rather than
in.nextInt()
or
in.nextFloat()
or
in.nextDouble()
, then how come there aren't 3 prompts to input the data for the 3 different function calls (of
hasNextInt()
and
hasNextFloat()
and
hasNextDouble()
)?

Answer

The scanner will try to parse the next input and if that succeeds the data type fits.

As an example have a look at the implementation of hasNextFloat():

public boolean hasNextFloat() {
    setRadix(10);
    boolean result = hasNext(floatPattern());
    if (result) { // Cache it
        try {
            String s = processFloatToken(hasNextResult);
            typeCache = Float.valueOf(Float.parseFloat(s));
        } catch (NumberFormatException nfe) {
            result = false;
        }
    }
    return result;
}

As you can see there are several steps involved:

  1. Check whether the input matches the pattern for floats, i.e. does it look like a float?
  2. If the input looks like a float, try to parse it. If that fails it wasn't a float, if it works it is at least a float (could be a double or even an int as well, that's why the code you posted checks for int, float and double in that order).