java - inputmismatch exception -
this question has answer here:
import java.util.*; public class ngg { static scanner numberentered; static scanner userinput = new scanner(system.in); static int guessednumber; static int randomnumber = (int) (math.random()* 11); static scanner reply; static string answer; public static void main(string[] args) { guesschecker(guessednumber); } public static void guesschecker(int userguess) { while (userguess != randomnumber) { intro(); userguess = intchecker(); if (userguess == randomnumber) { system.out.println("congradulations!"); system.exit(0); } else { system.out.println("that incorrect!"); delay(1000); retrychecker(reply, answer); } } } public static int intchecker() { try { return userinput.nextint(); } catch (inputmismatchexception e) { userinput.next(); system.out.println("your answer invalid!"); delay(2000); retrychecker(reply, answer); return 0; } } public static void retrychecker(scanner userreply, string userchoice) { system.out.println("would try again?"); userreply = new scanner(system.in); userchoice = userreply.nextline(); if (userchoice.equalsignorecase("yes") || userchoice.equalsignorecase("y")) { guesschecker(guessednumber); } else { system.exit(0); } } public static void intro() { system.out.println("i'm thinking of number in head..."); delay(1000); system.out.print("try guess it: "); } public static void delay(int millis) { try { thread.sleep(millis); } catch (interruptedexception e) {} } }
and here's problem:
i have number guessing game, every time says "try guess it:" let type in guess, unless previous guess string, letter or number, followed space , string, letter or number, instead of letting write own guess print out "your answer invalid" , move on program.
how fix this? userinput can string, letter or number, followed space , string, letter or number , it'll move 1 program normally.
the problem in intchecker()
.
public static int intchecker() { try { return userinput.nextint(); } catch (inputmismatchexception e) { userinput.nextline(); // -> changed .next() nextline() system.out.println("your answer invalid!"); delay(2000); retrychecker(reply, answer); return 0; } }
the reason when use next()
returns string when encounters space or eof.
so when give input it's me!
, first checks it's
, says it's wrong. asks whether continue or not next. when press y
goes method , reads remaining string me!
.
here have used different scanners userinput
, userreply
. userinput
static, object doesn't dies , has remaining string in me!
after returning its
.
so using nextline()
returns whole string.
for more info on how both work, check out other answer
i hope helped.
Comments
Post a Comment