我很抱歉,也许这是一个愚蠢的问题..
我需要获得正 double ,并防止向其中输入字符串(因此不会出现异常)。 我已经尝试过做一些有异常(exception)的事情,但更加困惑......
boolean check=false;
while (!check) {
if (PerConst.hasNextDouble() && !(PerConst.nextDouble()<0))
{
m = PerConst.nextDouble();
check=true;
}
else {
System.out.println("Invalid number, Enter positive double: ");
PerConst.next();
}}
因此,当我尝试(输入无法转换为 double 的字符串)或(小于零的 double )时,我需要收到一条消息“无效数字,输入正 double :”并再次输入(如果再次输入)不正确,然后一次又一次地收到该消息..
但在这种情况下(当我有该代码时)我有这个 intupr 和输出..
qw
Invalid number, Enter positive double:
rt
Invalid number, Enter positive double:
-12
Invalid number, Enter positive double:
-13 //ink why i have to enter 2 numbers..
-34
Invalid number, Enter positive double:
-1
-2
Invalid number, Enter positive double:
2 //this one is ok, but again i have to enter 2 more num, and just the last one counts
3
4
4.0 //i read that var after getting out of that loop
如果有人能帮助我,我将非常感激。 提前致谢
最佳答案
您正在循环中调用 nextDouble()
。
每次调用该方法时,都会返回下一个 double 值,您应该这样做:
boolean check=false;
while (!check && PerConst.hasNextDouble()) {
m = PerConst.nextDouble();
if (m >= 0)
check=true;
} else {
System.out.println("Invalid number, Enter positive double: ");
}
}
if(!check) {
// System.in has reached EOF
}
此循环仅调用一次 nextDouble,因此其值被保留
关于java - 防止将字符串输入到双变量中。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34993472/