Reputation: 1
So I'm writing code here just for fun but I've come up with an error that I just can't seem to fix. This block of code is supposed to take in an int... at first i had the hasNextInt() in the while loop alone to try and ensure i'm getting the correct input, but as fate would have it.. i got the exception. I then added a try catch to it thinking maybe i just did something wrong... and still i get the same error. I don't know whats wrong here. this is actually my 1st time using a try catch block (still kind of a noob). it looks good to me and i've looked at the documentation online and done some minor research but to no avail. can anyone identify whats wrong here? check it out:
do{
System.out.println("How much AP do you want to allocate towards HP? ");
try {//added try catch... still throwing the exception..
while(!in.hasNextInt()){//this should've been enough, apparently not
System.out.println("That is not a valid input, try again.");
in.nextInt();
}
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //trying to find specific reason.
}
hpInput = in.nextInt();
}while(hpInput < 0 || hpInput > AP);
if i entered a string it would give me the "That is not a valid input, try again." line.. but the exception would still occur right after instead of just looping until an actual int is detected... help plz..
Upvotes: 0
Views: 576
Reputation: 201439
Your while
loop should look something like this
while(!in.hasNextInt()){ // <-- is there an int?
System.out.println("That is not a valid input, try again.");
// in.nextInt(); // <-- there is not an int...
in.next(); // <-- this isn't an int.
}
Because the Scanner
doesn't have an int
.
Upvotes: 2
Reputation: 347204
You can't really validate the value in the Scanner
until something has been input, but once it's input, it's too late to validate it...
Instead, you could use a second Scanner
to validate the String
result you are getting from the user via the keyboard, for example
Scanner kbd = new Scanner(System.in);
int result = -1;
do {
System.out.println("How much AP do you want to allocate towards HP? ");
String value = kbd.nextLine();
Scanner validate = new Scanner(value);
if (validate.hasNextInt()) {
result = validate.nextInt();
}
} while (result < 0);
Upvotes: 0