With a Scanner you can check the token before reading it:
This will loop until the user types an integer number, rejecting strings or other numbers that cannot be read as integer.Code:Scanner sc = new Scanner(System.in); int n; do { System.out.append("Enter a number: "); if (sc.hasNextInt()) { n = sc.nextInt(); break; } else {System.out.format("%nERROR: %s is not an integer number!%n%n", sc.nextLine());} } while (true);




Reply With Quote