在我的验证方法中,如果用户输入字母而不是十进制值,我希望它打印一条错误消息,该方法确实在控制台上打印一条错误消息,但它打印两次,例如,如果我输入它打印出“dfdff”而不是小数:
“错误,号码无效。请重试”
“错误,号码无效。请重试”
如何让它在每次用户输入错误值时打印一次错误消息???
public static double getVaildSubtotal(Scanner sc)
{
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false)
{
if (sc.hasNextDouble())
{
subtotal = sc.nextDouble();
isValid = true;
}
else
{
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine();
if (isValid == true && subtotal <= 0)
{
System.out.println("Error! Number must be greater then 0.");
isValid = false;
}
else if (isValid == true && subtotal >= 10000)
{
System.out.println("Error! Number must be less then 10000.");
isValid = false;
}
}
return subtotal;
}
最佳答案
现在我才刚刚开始使用 Java,所以请对我温柔一些。
在我为类编写的一个小程序中,我遇到了类似的事情,所以我采用了这些原则:
public static double getVaildSubtotal(Scanner sc)
{
double subtotal = 0.0;
boolean isValid = false;
while (isValid != true)
{
String stSubTotal = sc.nextLine().trim();
int subTotalLength = stSubTotal.length();
boolean checkDouble = true;
for (int k = 0; k < subTotalLength; k++)
{
if (Character.isDigit(stSubTotal.charAt(k)) != true)
{
System.out.println("Error! Invalid decimal value. Try again.");
checkDouble = false;
}
}
if (checkDouble == true)
{
subtotal = Double.parseDouble(stSubTotal);
if (subtotal <= 0)
{
System.out.println("Error! Number must be greater then 0.");
}
else if (subtotal >= 10000)
{
System.out.println("Error! Number must be less then 10000.");
}
else
{
isValid = true;
}
}
}
return subtotal;
}
无论如何,就像这样,当条目吞噬整行时,每个条目只会得到一个错误代码。
但是,如果您对重建轮子不感兴趣(并且,老实说,我不会被侮辱),代码的当前问题是您的 sc.nextLine();现在,.nextLine()
"advances this scanner past the current line and returns the input that was skipped."
在这种情况下,这只是我的信念,你的 sc.nextLine();正在读取 .nextLine() 的输入,就像它应该的那样。所以当它转过来看里面有没有双的时候,没有,没有双,只有\n。
我建议删除 sc.nextLine();如果确实需要一个空格,希望它是 nextLine(),我会为 .nextLine() 添加另一个本地扫描仪;在验证方法中。
关于java - 得到两个相同的陈述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14847034/