public class Calculator
{
public static void main(String[] args)
{
boolean isValid = false;
Scanner myScanner = new Scanner(System.in);
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = myScanner.next();
while (isValid == false)
{
System.out.print("Enter Subtotal: ");
if (myScanner.hasNextDouble())
{
double sobTotal = myScanner.nextDouble();
isValid = true;
}
else
{
System.out
.println("Hay! Entry error please enter a valid number");
}
myScanner.nextLine();
}
}
}
Hi, im new to java, as usual im trying out a few things in the Scanner Class.
is there a way to see the input of the scanner?
Cuz i have a problem here with the code above as you'll see. this is the output of my console window after i entered wrong data. instead of numbers i entered KKK so can somebody explain me why i got this error message 2 times?
"this is the console"
Customer Type? (C/R) R
Enter Subtotal: KKK
Hay! Entry error please enter a valid number
Enter Subtotal: Hay! Entry error please enter a valid number
Enter Subtotal:
解决方案
The problem is you're calling scanner.nextdouble() which will work fine if and when there is a double in the input. When there is not a double in the input your input that was "KKK" is ignored by the call to nextDouble() and your error message is displayed then when you call nextLine() that same input "KKK" is still there waiting wo when you loop back throught the while the "KKK" is then passed back to your program and since it is still not a double you get the repeated error message.
Try this:
boolean isValid = false;
Scanner myScanner = new Scanner(System.in).useDelimiter("\\n");
String customerType = null;
System.out.print("Customer Type? (C/R) ");
customerType = myScanner.next();
while (!isValid)
{
System.out.print("Enter Subtotal: ");
if (myScanner.hasNextDouble())
{
double sobTotal = myScanner.nextDouble();
isValid = true;
}
else
{
System.out.println("Hay! Entry error please enter a valid number");
if(myScanner.hasNext()){
myScanner.next();
}
}
}
That will consume the invalid input of "KKK" and let the program continue properly.