简体   繁体   English

扫描仪异常处理

[英]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(); 试试这个:-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/ 有关更多信息: https : //itaehun.wordpress.com/2010/09/30/flush-in-java-when-using-nextline/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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