Because the string or character you entered isn't a numeric digit: if it isn't, it can't be parsed to a number!
Put a
while
loop around the
print
and
parseInt
calls, and a
try ... catch
block as well. Move your
return
to after the
parseInt
call, and it will loop until the user enters a number.
while(true) {
try {
...your stuff...
return data;
}
catch(Exception e) {}
}
Also, see here:
Java.util.Scanner.nextInt() Method | Tutorialspoint[
^]
Replace this:
data= Integer.parseInt(scanner.nextLine());
With this:
data= scanner.nextInt();
And let the system do the work.