[英]How to verify if user's input is a double or an integer?
我正在编写一个程序,该程序可以识别数字是否是一个完美的平方。 显然,理想平方的因数必须是整数。 所以我想知道识别用户输入(通过Scanner
)的sqrt是integer
还是double
的最佳方法是什么?
提前致谢。
我假设您的代码包含以下语句:
Scanner userIn = new Scanner(System.in);
//userIn.next() somewhere in your code, which is what you want to test
您可以使用以下方法(将userIn.next()作为参数传递):
public boolean isDouble(String userInput){
if(userInput.contains(".")){
return true;
}
else{
return false;
}
}
此代码基本上检查userInput字符串是否包含小数点,如果是,则输入为双精度值,否则为假,还可以添加初步条件,以确保userInput是数字而不是其他任何值。
编辑: 正如克里托斯·基里亚库(Klitos Kyriacou)在评论中正确指出的那样,我的回答最初并未回答所提出的问题,但是OP感到满意...为了完整起见,我将具体回答这个问题:
静态类Math中的sqrt方法返回一个double,因此使用上面的测试将不起作用,因为Math.sqrt(25)将返回5.0。
为此,只需将sqrt返回值的舍入值与sqrt方法的实际返回值进行比较即可。
您可以使用以下方法(与上面的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.