3
private double inputReader(){
    Scanner scanner = new Scanner(System.in).useLocale(Locale.US);

    while(true){
        System.out.println("Input: ");
        try {
            double value = scanner.nextDouble();
            return value;
        } catch (InputMismatchException e){
            System.out.println("It's not a number");
        }
    }
}

This method is responsible for scanning input. It throws InputMismatchException when user gives string or something that is not a number. The problem is that when user gives a bad input, it creates a infinite loop resulting in something like this in console:

It's not a number

Input:

It's not a number

Input:

It's not a number

Input:

It's not a number

and so on For me it looks like scanner is reading the same value over and over again, but I don't know how to fix it. I want to make the program asking user for input until he finally gives a correct number.

Pawlinho
  • 69
  • 1
  • 7
  • 1
    Try `Double.parseDouble(scanner.nextLine())` instead. The user enters a full line of input, not just a number (in particular, there is a trailing `\n` at the end). – Zabuzard Jul 29 '21 at 10:50
  • 1
    @Zabuzard now it's working correctly. Thanks – Pawlinho Jul 29 '21 at 10:54

0 Answers0