1

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

  • 1
    You can check this question: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo Looks like you're having the same issue. – Adam Barreiro Oct 14 '20 at 17:18
  • 1
    When you try to read a double that is improperly formatted with nextDouble(), the file pointer is not moved ahead. So when you read another string with next(), it takes the malformed double, which is an acceptable string. – NomadMaker Oct 14 '20 at 18:38

0 Answers0