Ahmed Helal Ahmed Ahmed Helal Ahmed - 2 months ago 18
Java Question

hasNextDouble method give true with integer the same as double

First of all, see this code:

package test;

import java.util.*;

public class hasnext {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);

If i enter integer number I will get true ex : 5

If i enter real number I will get true then crash ex 1.5

The method gives true either the number of type double or integer is that right and why?


From the javadoc for Scanner.hasNextDouble():

Returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method.

An integer can be interpreted as a double. For instance, in Java you can cast an integer to a double, with no loss of information.

Apparently a double can't be interpreted as an integer. Most likely because in most cases, the double would lose information by converting from a double to an integer.