Suppose I need to keep on asking the user till he enters a double
.
What I did is I used a while loop and checking if there is an exception or not.
If there is an exception, I would go and ask for the next input.
double bal = 0;
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println("Enter the balance");
bal = sc.nextDouble();
break;
} catch (Exception e) {
System.out.println("That isn't a number");
}
}
System.out.println("Bal is " + bal);
sc.close();
But if I enter a non-double then it doesn't ask for the next input, keeps on printing those two lines ending in an infinite loop.
Enter the balance
XYZ
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
Enter the balance
That isn't a number
....
What is that I'm missing?