Clearing input buffer when using a Scanner

18,184

Solution 1

You can clear the input from catch block. If you do not want anything other than integer then just do inputStream.nextLine(); in your catch block.

Here is a generic snippet for taking only integer input.

private static int takeOnlyIntegerInput() {
        Scanner keyboard = new Scanner(System.in);
        boolean isValid = false;
        int num=-1;
        while (isValid == false) {
            System.out.print("Please enter an: ");
            try {
                num = keyboard.nextInt();
                isValid = true;
            } catch (InputMismatchException ex) {
                System.out.println("Wrong input. Ony integer input will be processed.");
                //clean up the garbage input
                keyboard.nextLine();
            }finally{
                keyboard.close();
            }
        }
        return num;
    }

Solution 2

You should add, in your exception's catch clause, either data.next() or data.nextLine().

Which of them to choose depends on the sort of input and what kind of mistakes you expect. If you expect more input on the same line, for example:

XXXX 1234
5678

then only data.next() will work correctly, because it will skip the XXXX and the next token will be 1234 which is what you want.

If you use data.nextLine() in this case, then both XXXX and 1234 will be skipped - everything until the end of the line, and the next token to be read will be 5678.

Share:
18,184
ANUPAM
Author by

ANUPAM

I just love any kind of computer, love to code computer programming to create new things, new approaches!!

Updated on June 04, 2022

Comments

  • ANUPAM
    ANUPAM almost 2 years

    I have a java code, and there I want to take an integer from user. If that input is an integer really then its fine the control will go through next, but if the input is other than an integer the control will go for the scanning again. The problem is when other than an integer is being given by user the while loop is being looped again and again. How to solve? Please help me out.

    I have tried the question answer in this site but have not got any result.

    Here is my code-

    import java.io.* ;
    import java.util.Scanner;
    
    class A{ 
        int name;
        int take_int(){
    
            Scanner data=new Scanner(System.in);
            //BufferedWriter BW=new BufferedWriter();
    
    
        while(true){
            int fault_res=0 ;
            try{
                System.out.print("Enter A Number : ");
                //BW.flush();           
                name=data.nextInt(); // comment : if user give an alphabet
                                     // then the control rounds again and
                                     // again, how to solve? System is not
                                     // taking any input after entering
                                     // any alphabet first time, but it 
                                     // should take as per my code, I
                                     // think is is happening due to i/p
                                     // buffer,  unable to delete it. 
    
            }
            catch(Exception E){
                System.out.println("\nSomething Went Wrong !!\nRetry Please !!!");
                fault_res=1 ;
            }
            if(fault_res==0){break ;}
        }
        System.out.println("\nnumber at other class "+name);
        return name ;
        }
    }
    class sn{
        public static void main(String args[]){
            A obA=new A();
            int number=obA.take_int();
            System.out.println("\nYou have entered "+number);
        }
    }