简体   繁体   中英

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);
    System.out.println(s.hasNextDouble());
    s.nextInt();
  }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM