Vswe's Summer Courses | You're not logged in. Sign up or log in | Server time: | Donate
One can now see other persons' badge hunts. Simply head over to their profiles to access them.

Go back to course page

Thinking with objects

Object orientated programming in Java

Help!

  • 2013-08-27 14:17:41
    I have a problem with this exception.
    It starts to make a infinite loop
    int i=0;
            while(i<=0||i>5){
                try{
                i=input.nextInt();
                }
                catch(InputMismatchException e){
                    i=-1;
                }
                if(i<=0||i>5){
                    System.out.println("Incorrect number");
                }
            }
  • 2013-08-27 14:18:38
    This exception is if the user inserts a letter instead of a number
  • 2013-08-27 14:36:40
    You need to clear the buffer for the letter. Otherwise it will crash every time you do input.nextInt()
  • 2013-08-27 22:30:10
    It starts to say incorrect number infinite times
  • 2013-08-27 23:10:36
    You'll have to clear the input buffer. Might be a tricky to make it work perfectly.

    I showed how to make a method that retrieved valid integers in a specific range in the end of the first course.
  • 2013-08-28 00:51:53
    Can you pass me the link of that lecture?
  • 2013-08-28 01:26:04
    But i dont need to control the integer that the user inserts. I need to control that the user inserts a letter insetd of numers
  • 2013-08-28 01:31:04
    The method is in the end of this file

    https://dl.dropboxusercontent.com/u/46486053/ValidIntegerExample.java
  • 2013-08-28 07:39:17
    when you enter a letter, the method nextInt() throws the error before clearing the buffer like it usually does. a quick and dirty way to fix it is to do input.next() inside your catch block. however, it will cause problems when you enter multiple words so i highly recommend you not to do that.

    you should just use Vswe's method to get a valid integer. it works perfectly fine and there is no problem with it so there is no reason not to use it.
  • Log in or sign up to reply to this thread