java - Confusion with an infinite while loop, concerning Scanner.nextInt(); -


i having problems understanding why code not working. objective keep reading input of user until user enters "5", code continue. appreciate there better ways, , open suggestions of more concise ways go (trying parse string, perhaps), question more curious why method not work opposed looking better method.

the code works when integer input, if enter string, code loops continuously, , catch block started without input required. presume it's feature of scanner retaining input, i'm not sure.

my code following:

import java.util.scanner; import java.util.inputmismatchexception;  public class app {     public static void main(string[] args) {          int temp = 0;         system.out.println("enter number 5: ");          while (temp != 5) {             try {                 temp = sc.nextint();             } catch (inputmismatchexception e) {                 system.out.println("try again!");             }         }         system.out.println("got it!");         sc.close();     } } 

if next thing read not integer, nextint doesn't read anything. if type "hi", nextint throws inputmismatchexception, , program calls nextint again. that call still throws inputmismatchexception, because next thing read still "hi", isn't integer. program calls nextint again, , throws exception again exact same reason. , on.

one possible solution call sc.next(), , ignore result:

        try {             temp = sc.nextint();         } catch (inputmismatchexception e) {             sc.next(); // ignore whatever user typed wasn't integer             system.out.println("try again!");         } 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -