我对 Java 还很陌生,我正在尝试进行数据验证。当我使用有效数据时,代码运行良好,但是当我输入字符串而不是整数时,代码只会永远循环。它只是循环“输入错误。请输入一个数字”。提前致谢!
//Get input from user
System.out.print("What is your name (Last, First)? ");
String name = scan.nextLine();
System.out.print("enter a date:");
String datein = scan.nextLine();
boolean valid = false;
while (valid != true)
{
System.out.print("Electricity used (KW):");
if (scan.hasNextDouble())
{
electricityUsed = scan.nextDouble();
valid = true;
}
else
System.out.println("Bad input. Please enter a number.");
}