简体   繁体   中英

Scanner exception handling

I'm trying to do some simple program and there is a little thing that I curious about at exception handling.

Thus a piece of my code

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                System.out.println("Input Mismatch, try again");
            }
            while (rep == 0);

and then another code

do{
       System.out.println(helloWorld.line);

            System.out.print("Value a : ");
            try{
                if(scan.hasNextInt())
                    rep++;
                a = scan.nextInt();
            }
            catch (InputMismatchException e){
                rep = 0;
                scan.next();
                JOptionPane.showMessageDialog(null,"Input 
                mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
            }
            while(rep == 0);

I'm doing a piece of code for ignoring the wrong input and do a loop until the scanner read the correct input also give a popup message. The question is that the first code works as intended, the second piece is running but doing nothing after the first input and the program not terminated. Why?

Try this:- scan.nextLine(); this line will clear the buffer

do{
   System.out.println(helloWorld.line);

        System.out.print("Value a : ");
        try{
             scan.nextLine();
            if(scan.hasNextInt())
                rep++;
            a = scan.nextInt();
        }
        catch (InputMismatchException e){
            rep = 0;
            scan.next();
            JOptionPane.showMessageDialog(null,"Input 
            mismatch","Error",JOptionPane.INFORMATION_MESSAGE);
        }
        while(rep == 0);

For more info: https://itaehun.wordpress.com/2010/09/30/flush-in-java-when-using-nextline/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM