简体   繁体   English

Java:检查double的输入,但它接受一个int并将其变为double

[英]Java: Checking input for a double, but it accepts an int and turns it into a double

So I'm trying to run this program that will check each input to see that the input matches the correct type, int, double, and boolean. 所以我试图运行这个程序来检查每个输入,看看输入是否匹配正确的类型,int,double和boolean。 However, the double value is giving me trouble. 然而,双重价值给我带来了麻烦。 The hasnextDouble accepts an int and the variable turns it into a double. hasnextDouble接受一个int,变量将其变为double。 Any help I can get to solve this would be appreciated, along with the explanation as to why, I don't just want an answer, I want to understand. 我可以得到任何帮助来解决这个问题,以及解释为什么,我不仅仅想要一个答案,我想理解。

import java.util.Scanner;

public class TestValidInput
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
    int anInt = 0;
    double aDouble = 0.0;
    boolean aBoolean = false;

    System.out.printf("%nEnter an integer:  ");

    while(!input.hasNextInt())
    {
      input.next(); 
      System.out.printf("%nYou must only enter an integer:  ");
    }

    anInt = input.nextInt();

    System.out.printf("%n%d%n", anInt); 

    System.out.printf("%nEnter a double:  ");

    while(!input.hasNextDouble())
    {
      input.next();  
      System.out.printf("%nYou must only enter a double:  ");
    }

    aDouble = input.nextDouble(); 

    System.out.printf("%n%f%n", aDouble); 

    System.out.printf("%nEnter a true or a false:  ");

    while(!input.hasNextBoolean()) 
    {
      input.next();  
      System.out.printf("%nYou must only enter a TRUE or FALSE:  ");  
    }

    aBoolean = input.nextBoolean();  

    System.out.printf("%n%b%n", aBoolean);  

    input.close();

    System.exit(0);
  }
}

The space of doubles are a superset of integers, ie and int can fit into a double, or be interpreted as such. 双精度空间是整数的超集,即int可以拟合成double,或者可以解释为double。 if you specifically need decimal point in the number you should check for that instead. 如果您在数字中特别需要小数点,则应该检查该数字。

Explanation why 解释原因

with the explanation as to why 解释为什么

Because int value can be represented as double value, in java integer value can be implicitly converted to double, but not vice versa: 因为int值可以表示为double值,所以在java中整数值可以隐式转换为double,但反之则不然:

double d = 1.0; // valid
double dd = 1; // valid
int i = 1; // valid
int ii = 1.0; // error

How to solve 怎么解决

Any help I can get to solve this 我可以帮助解决这个问题

Add check that it's not in integer format: 添加检查它是否为整数格式:

while(!(input.hasNextDouble() && !input.hasNextInt()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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