0

I wanted to write a simple program that asks for a number, if the user inputs a number it will end, otherwise it will print an error and ask again for a number. The problem is that my program just keeps printing the error message ("Not a valid input. Error :null") and never asks for a number again.

import java.util.InputMismatchException;
import java.util.Scanner;


public class Numbers {
    public static void main(String[] args){
        number();

    }
    public static int number() {
        System.out.print("Enter a number: ");
        Scanner readLine = new Scanner(System.in);
        boolean isInteger = false;
        while (!isInteger) {
            try {
                int numbers = readLine.nextInt();
                System.out.println(numbers);
                isInteger = true;
            } catch (InputMismatchException e) {
                System.err.println("Not a valid input. Error :" + e.getMessage());
            }

        }

        return 0;
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
tim123
  • 15
  • 2

1 Answers1

1
    Scanner sc = new Scanner(System.in);
    while (sc.hasNext()) {
        if (sc.hasNextInt()) {
            int number = sc.nextInt();
            System.out.println(number);
        } else {
            System.err.println("Not a valid input. Error :" + sc.next());
        }
    }
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138