简体   繁体   English

如何验证用户输入是双精度还是整数?

[英]How to verify if user's input is a double or an integer?

I am writing a program that recognizes if a number is a perfect square. 我正在编写一个程序,该程序可以识别数字是否是一个完美的平方。 Obviously the factors of the perfect square have to be integers. 显然,理想平方的因数必须是整数。 So I was wondering what would be the best way to recognize whether the sqrt of the user input (via Scanner ) is an integer or a double . 所以我想知道识别用户输入(通过Scanner )的sqrtinteger还是double的最佳方法是什么?

thanks in advance. 提前致谢。

I'm assuming your code contains the following statements: 我假设您的代码包含以下语句:

      Scanner userIn = new Scanner(System.in);
    //userIn.next() somewhere in your code, which is what you want to test

You could use the following method (pass userIn.next() as an argument): 您可以使用以下方法(将userIn.next()作为参数传递):

        public boolean isDouble(String userInput){
               if(userInput.contains(".")){
                     return true;
               }
               else{
                    return false;
               }
        }

This code basically checks if the userInput String contains a decimal point, if so the input is a double else it would be a false, you could also add preliminary conditions to make sure that the userInput is a number and not anything else. 此代码基本上检查userInput字符串是否包含小数点,如果是,则输入为双精度值,否则为假,还可以添加初步条件,以确保userInput是数字而不是其他任何值。


EDIT: As Klitos Kyriacou has rightfully pointed out in the comments, my answer did not initially answer the question asked, however the OP was satisfied... for the sake of completeness, I will answer the question specifically: 编辑: 正如克里托斯·基里亚库(Klitos Kyriacou)在评论中正确指出的那样,我的回答最初并未回答所提出的问题,但是OP感到满意...为了完整起见,我将具体回答这个问题:

The sqrt method from the static class Math returns a double, so using the test above will not work as Math.sqrt(25) will return 5.0. 静态类Math中的sqrt方法返回一个double,因此使用上面的测试将不起作用,因为Math.sqrt(25)将返回5.0。

To go about this one can simply compare the rounded value of the sqrt's return value to the actual return value of the sqrt method. 为此,只需将sqrt返回值的舍入值与sqrt方法的实际返回值进行比较即可。

You could use the following method (As in the case above userIn.next(), will be the argument to the method): 您可以使用以下方法(与上面的userIn.next()一样,将是该方法的参数):

 public boolean isPerfectSquare(String userInput){
        if(Math.sqrt(Double.parseDouble(userInput)) == Math.round(Math.sqrt(Double.parseDouble(userInput)))){
            return true;
        }
        return false;
    }

计算平方根,并将其与自身转换为整数Math.floor()如果数字可能很大Math.floor()Math.floor()的结果进行比较。

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

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