Jump to content
  • Advertisement
Sign in to follow this  
Uberskull85

Of scanners, trys and exceptions

This topic is 3785 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Greetings y'all. I was wondering if any of you guys could help me with a particular problem. As an exercise in a Java programming course I am supposed to create a new class, which uses the original java.util Scanner class, called EasyScanner. In this class are static methods which allow the user to scan in integer and double inputs. These methods are supposed to use exception handling to deal with incorrect inputs from the user. Here is a code example: public static int nextInt() { int i = 0; boolean inputIsCorrect = false; Scanner sc = new Scanner(System.in); while(inputIsCorrect == false) { try { System.out.println("Trying"); i = sc.nextInt(); System.out.println("Input accepted"); inputIsCorrect = true; } catch(InputMismatchException e) { System.out.println("Exception caught"); inputIsCorrect = false; } } return i; } There is a problem with this. Whenever the user inputs an invalid value, say the character a, an infinite loop occurs. For some reason the nextInt() method of the scanner object never gets called beyond the first iteration of the loop. What could I be doing wrong here? Would you need more information? The output I get is: Trying Exception caught trying Exception caught etc. Thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!