while learning the core syntax of Java I have encountered an error preventing me from taking user input through the console, here is my code:
Scanner sc = new Scanner(System.in);
String ans;
do {
System.out.print("Enter a number: ");
try {
double input = sc.nextDouble();
System.out.printf("%.2f^2 = %.2f%n", input, Math.pow(input, 2));
} catch (Exception e) {
System.out.println("Invalid input, try again !");
} finally {
System.out.print("Continue ? [y/n] ");
ans = sc.next();
System.out.printf("%nans value in `finally` block: %s", ans);
}
} while (ans.equalsIgnoreCase("y"));
this prompts the user to enter a double then displays the square of that number, simple, but problem occurs when entering an invalid input, I have implemented an exception handler for such case, but what happens is that the scanner in the finally
block doesn't wait for user input, instead, it gets automatically assigned whatever the user inputs on the try
block, here is an output example:
Enter a number: foo
Invalid input, try again !
Continue ? [y/n]
ans value in `finally` block: foo
Process finished with exit code 0
I could get around the issue by using this instead
double input = Double.parseDouble(sc.nextLine());
and
ans = sc.nextLine();
but I still have no idea on where the issue comes from