Scanner
requires you to check the kind of input it sees before you call the nextXyz
method.
if (lines != int)
Once you call nextInt()
, it is too late to check what kind of input you have: in order for nextInt
to succeed, there must be an int
available at the current point; otherwise an exception would be thrown.
Use hasNextInt
method to check what you have at the current point in the input buffer:
if (input.hasNextInt()) {
lines = input.nextInt();
} else {
System.out.println("Please enter a number");
input.nextLine(); // Drop the current input up to the end-of-line marker
}